Guillermo Bastian
Guillermo Bastian

Reputation: 83

Xpath Selenium- How to locate a element by the sub text

Hope you´re really fine and can help me with this short question. I´m trying to locate the following object id=C39_W133_V136_thtmlb_button_27 but using the text that is located after an span (text = "Edit"). Please I tried different ways but didn´t work till now, any idea?

<a href="javascript:void(0)" class="th-bt th-bt-icontext-dis icon-font" tabindex="-1" oncontextmenu="return false;" ondragstart="return false;" id="C39_W133_V136_thtmlb_button_27">
  ::before  
  <img class="th-bt-img" src="/SAP/BC/BSP/SAP/thtmlb_styles/sap_skins/belize/images/1x1.png">  
  <span class="th-bt-span"><b class="th-bt-b">Edit</b></span>  
  <b class="th-bt-b">Edit</b>
</a>

Upvotes: 2

Views: 648

Answers (2)

JeffC
JeffC

Reputation: 25744

In order to locate an element using text contained in an element, the only option is to use XPath.

//a[./b[.='Edit']]
^ Start at the top of the document and find an A tag
   ^ ...that has a descendant B tag
        ^ ...that contains the text 'Edit'

Upvotes: 2

undetected Selenium
undetected Selenium

Reputation: 193388

To locate the <a> element which have a descended <span> with text as Edit you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@id, 'thtmlb_button')][.//b[text()='Edit']]")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Upvotes: 0

Related Questions