简体   繁体   English

查找所有以'button-'开头的元素

[英]Find all elements that start with 'button-'

I am using Selenium to try and get all ID elements that that start with "button-". 我正在使用Selenium尝试获取以“ button-”开头的所有ID元素。 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 . 到目前为止,我尝试使用正则表达式来匹配“ button-”,但是我收到一条错误消息,指出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.? 当您不知道完整的ID,类,css选择器等时,获取所有元素的适当方法是什么?

You could use find_element_by_xpath and starts-with : 您可以使用find_element_by_xpathstarts-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- [starts-with(@id, "button-")]将过滤具有以button-开头的属性id的元素

Clément's answers works just fine, but there is also a way to do this with css selectors: Clément的答案很好用,但是也可以使用CSS选择器来做到这一点:

*[id^='button']. 

* matches all tags, just like in xpath and ^= means 'starts with' *匹配所有标签,就像在xpath中一样,并且^=表示“开头为”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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