How can I find element by text but it's number in selenium

600 Views Asked by At

I want to get an element by text, but it is number? I guess? For example,

<a class="ui-state-default" href="#">11</a>

It contain a number so this code didnt work

driver.find_element_by_xpath('//*[@text="11"]')

How can I find this element?

3

There are 3 best solutions below

0
On BEST ANSWER

You can access a web element(i.e div tag in this case) by its text content this way:

driver.find_elements_by_xpath("//*[contains(text(), '11')]")
0
On

To locate the element by it's text you can use either of the following based Locator Strategies:

  • Using xpath and text():

    element = driver.find_element_by_xpath("//*[text()='11']")
    
  • Using xpath and contains():

    element = driver.find_element_by_xpath("//*[contains(., '11')]")
    

Ideally, to locate the element 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[@class='ui-state-default' and text()='11']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='ui-state-default' and contains(., '11')]")))
    
  • 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
    
0
On
driver.find_element_by_xpath('//*[contains(text,"11")]')

Please use above xpath to workout with this element