如何单击包含可见文本且可通过 Python 使用 Selenium 单击的元素

How to click an element that contains visible text and is clickable with Selenium with Python

要单击的元素仅基于它包含的文本(其他):

<a class="blah" href="/some_page/"><span>15</span> others</a>

失败的项目:

driver.find_element(By.XPATH, "//*[contains(text(), ' others')]").click()

错误:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(text(), 'others')]"}

要找到 clickable 元素,您需要引入 WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.blah[href='/some_page/'] > span"))).click()
    
  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='blah' and @href='/some_page/'][contains(., 'others')]"))).click()
    
  • 注意:您必须添加以下导入:

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

参考资料

您可以在以下位置找到关于 的一些相关讨论:

DebanjanB 的答案的另一个替代方案,使用受 XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

启发的不同 xpath
"//*[text()[contains(.,' others')]]"