Home > Back-end >  Find elements by xpath using regex
Find elements by xpath using regex

Time:09-17

I'm tryin to use selenium to find elements using Xpaths, can I create a rule for all these Xpaths using the "contains()" method:

//*[@id="jsc_c_10"]/span
//*[@id="jsc_c_11"]/span
//*[@id="jsc_c_4n"]/span
//*[@id="jsc_c_2o"]/span

I was trying

driver.find_element_by_xpath("//*[contains(@id,'jsc_c_* ')]")

with no success

CodePudding user response:

Direct regex is not supported in Selenium that usage xpath v1.0.

You can use find_elements instead with contains as below.

list_of_elements = driver.find_elements_by_xpath("//*[contains(@id,'jsc_c_')]/span")

and can iterate it like this :

for ele in list_of_elements:
    print(ele.text)

Note that ele is a web element, you can do stuff like .text or .click() etc.

or even first try to print the size like print(len(list_of_elements))

CodePudding user response:

driver.find_element_by_xpath("//*[starts-with(@id,'jsc_c_')]")

xpath doesn't support regex , you can use starts-with method instead

Link all functions can that are supported in xpath can be seen in this link

  • Related