Xpath Selenium-如何通过子文本定位元素

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

希望你真的很好,可以帮助我解决这个简短的问题。 我试图找到以下对象 id=C39_W133_V136_thtmlb_button_27 但使用位于跨度之后的文本(文本 =“编辑”)。请问我尝试了不同的方法,但直到现在都没有用,知道吗?

<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>

要使用元素中包含的文本定位元素,唯一的选择是使用 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'

要找到 <a> 元素,其后代 <span> 文本为 Edit 您需要引入 for the visibility_of_element_located() and you can use either of the following :

  • 使用XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@id, 'thtmlb_button')][.//b[text()='Edit']]")))
    
  • 注意:您必须添加以下导入:

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