简体   繁体   中英

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")]')

Try using CSS selector instead of Xpath:

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

(because CSS has "starts with" selector ).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM