Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 table with selenium python web driver. It has Syntax

driver.find_element_by_xpath('//*[@id="isc_43table"]/tbody/tr[1]/td[11]').click();

help me editing this syntax to match it with table ending id with "table". (only one table is generated).

like image 344
gurpreet bal Avatar asked Mar 06 '23 18:03

gurpreet bal


2 Answers

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
like image 107
undetected Selenium Avatar answered Mar 10 '23 12:03

undetected Selenium


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.

like image 24
Titus Avatar answered Mar 10 '23 11:03

Titus