user6062083
user6062083

Reputation:

selenium python How can I find all ID elements that begin the same

How can I assign all elements that begin with the same id part to a list? I have elements ids that are 'card0', 'card1', 'card2' and I want to put all of them in a list. I have tried

cards = []
cards = driver.find_elements(By.XPATH, '//*[contains(@id, "card")]')

I can find the first one by using

cards = driver.find_element(By.XPATH, '//*[contains(@id, "card0")]')

Upvotes: 0

Views: 679

Answers (2)

Razvan
Razvan

Reputation: 387

Use stars-with function from xpath as well:

//*[starts-with(@id, "card")]

And to be more precise, avoid using * if you want to collect similar elements, and replace it with div, input, li etc (whatever you have there)

Upvotes: 1

Mate Mrše
Mate Mrše

Reputation: 8394

Try using CSS selector instead of Xpath:

cards = driver.find_elements_by_css_selector("[id^=card]")

(because CSS has "starts with" selector).

Upvotes: 0

Related Questions