Selenium如何定位ID以single_button开头、后缀随机的按钮元素
实现方案
find_element_by_id()仅支持完全匹配id的完整值,无法直接做前缀模糊匹配,你可以用CSS选择器或XPath的匹配规则实现定位,以下是两种可行写法:
方法1:CSS选择器(更简洁,推荐)
CSS选择器支持^=语法匹配属性值前缀,写法如下:
# Selenium 3 旧版API写法 button = driver.find_element_by_css_selector('button[id^="single_button"]') # Selenium 4 官方推荐写法(需提前导入By类) from selenium.webdriver.common.by import By button = driver.find_element(By.CSS_SELECTOR, 'button[id^="single_button"]')
其中id^="single_button"表示匹配所有id以single_button为前缀的元素,你提到页面内仅有1个符合规则的元素,直接调用即可定位到目标按钮。
方法2:XPath匹配
也可以用XPath的starts-with()函数实现相同效果:
# Selenium 3 旧版API写法 button = driver.find_element_by_xpath('//button[starts-with(@id, "single_button")]') # Selenium 4 官方推荐写法 from selenium.webdriver.common.by import By button = driver.find_element(By.XPATH, '//button[starts-with(@id, "single_button")]')
内容的提问来源于stack exchange,提问作者BABELAERE Robin
相关产品推荐
相关产品推荐

