Amir Katorza
Amir Katorza

Reputation: 35

Find elements by xpath using regex

I'm trying to use selenium to find elements using Xpaths

Can I create a rule for all these Xpaths using the contains() method

My Xpaths list :

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

I tried the following code with no success:

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

Upvotes: 1

Views: 423

Answers (2)

PDHide
PDHide

Reputation: 19939

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

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

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))

Upvotes: 1

Related Questions