You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:56:12