简体   繁体   中英

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>

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM