簡體   English   中英

查找所有以'button-'開頭的元素

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

我正在使用Selenium嘗試獲取以“ button-”開頭的所有ID元素。 到目前為止,我嘗試使用正則表達式來匹配“ button-”,但是我收到一條錯誤消息,指出TypeError: Object of type 'SRE_Pattern' is not JSON serializable 到目前為止,我的代碼是:

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

但是如上所述,這會引發錯誤。 當您不知道完整的ID,類,css選擇器等時,獲取所有元素的適當方法是什么?

您可以使用find_element_by_xpathstarts-with

find_elements_by_xpath('//*[starts-with(@id, "button-")]')
  • //*將匹配任何元素
  • [starts-with(@id, "button-")]將過濾具有以button-開頭的屬性id的元素

Clément的答案很好用,但是也可以使用CSS選擇器來做到這一點:

*[id^='button']. 

*匹配所有標簽,就像在xpath中一樣,並且^=表示“開頭為”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM