Skip to content Skip to sidebar Skip to footer

How To Find Element Based On What Its Value Ends With In Selenium?

I am dealing with a situation where every time I login a report is displayed in a table whose ID is dynamically generated with random text ending with 'table'. I am automating this

Solution 1:

The ends-with XPath Constraint Function is part of XPath v2.0 but as per the current implementation Selenium supports XPath v1.0.

As per the HTML you have shared to identify the element you can use either of the Locator Strategies:

  • XPath using contains():

    driver.find_element_by_xpath("//*[contains(@id,'table')]/tbody/tr[1]/td[11]").click();
    
  • Further, as you have mentioned that table whose ID is dynamically generated so to invoke click() on the desired element you need to induce WebDriverWait for the element to be clickable and you can use the following solution:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(@id,'table')]/tbody/tr[1]/td[11]"))).click()
    
  • Alternatively, you can also use CssSelector as:

    driver.find_element_by_css_selector("[id$='table']>tbody>tr>td:nth-of-type(11)").click();
    
  • Again, you can also use CssSelector inducing WebDriverWait as:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[id$='table']>tbody>tr>td:nth-of-type(11)"))).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

Solution 2:

I hope, either these 2 will work for you

driver.find_element_by_xpath("//table[ends-with(@id,'table')]/tbody/tr[1]/td[11]").click();

OR

driver.find_element_by_xpath("//table[substring(@id,'table')]/tbody/tr[1]/td[11]").click();

If not getting, remove the tags from tbody.

For such situations, when you face randomly generated ids, you can use the below functions with XPATH expression

1) Contains,

2) Starts-with &

3) Ends-with

4) substring

Syntax

//table[ends-with(@id,'table')]

//h4/a[contains(text(),'SAP M')]

//div[substring(@id,'table')]

You need to identify the element which is having that id, whether its div or input or table. I think its a table.


Solution 3:

You can try below XPath to simulate ends-with() syntax:

'//table[substring(@id, string-length(@id) - string-length("table") +1) = "table"]//tr[1]/td[11]'

You can also use CSS selector:

'table[id$="table"] tr>td:nth-of-type(11)'

Post a Comment for "How To Find Element Based On What Its Value Ends With In Selenium?"