0

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

<a class="blah" 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')]"}
vitaliis
  • 4,082
  • 5
  • 18
  • 40

2 Answers2

1

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:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

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')]]"
FunkySayu
  • 7,641
  • 10
  • 38
  • 61