Python与Selenium XPath多条件选择语法错误排查求助
修正你的Selenium XPath语法问题
嘿,我一眼就看出你的XPath哪里错啦!你在第二个条件外面多套了一层方括号,这才导致了语法错误。XPath里多条件组合直接用and连接两个条件表达式就行,不需要额外嵌套括号。
正确的代码写法
choices = driver.find_elements_by_xpath("//div[contains(.,'5') and contains(@class, 'option')]")
额外小提示(针对Selenium 4+版本)
如果你用的是Selenium 4及以上版本,find_elements_by_xpath这类旧方法已经被官方弃用啦,更推荐使用新的写法,需要先导入By模块:
from selenium.webdriver.common.by import By choices = driver.find_elements(By.XPATH, "//div[contains(.,'5') and contains(@class, 'option')]")
另外,如果你的需求是精确匹配class属性值(而不是包含),可以把contains(@class, 'option')改成@class='option',根据你的实际场景调整就好~
内容的提问来源于stack exchange,提问作者Noah Ratliff
相关产品推荐
相关产品推荐

