简体   繁体   中英

Find all elements that start with 'button-'

I am using Selenium to try and get all ID elements that that start with "button-". What I have tried so far was to use regex to match the "button-" but I get an error stating that TypeError: Object of type 'SRE_Pattern' is not JSON serializable . My code so far is:

all_btns = self.driver.find_elements_by_id(re.compile('^button-?'))

But as mentioned that raises an error. What is the appropriate way of getting all elements when you don't know the full ID, class, css selector etc.?

You could use find_element_by_xpath and starts-with :

find_elements_by_xpath('//*[starts-with(@id, "button-")]')
  • //* will match any elements
  • [starts-with(@id, "button-")] will filter the elements with a property id that starts with button-

Clément's answers works just fine, but there is also a way to do this with css selectors:

*[id^='button']. 

* matches all tags, just like in xpath and ^= means 'starts with'

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