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

Time:12-20

The element to be clicked based ONLY on the text it contains (others):

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

The item that fails:

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

The error:

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

CodePudding user response:

An additional alternative from DebanjanB's answer using a different xpath inspired from XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

"//*[text()[contains(.,' others')]]"

CodePudding user response:

To locate the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

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

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='blah' and @href='/some_page/'][contains(., 'others')]"))).click()
    
  • 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
    

References

You can find a couple of relevant discussions on NoSuchElementException in:

  • Related