使用Selenium+Python定位元素ID时触发InvalidSelectorException求助
问题解决方法
你触发InvalidSelectorException的核心原因是定位方式与选择器语法不匹配:
- 当
find_element的第一个参数指定为'id'时,第二个参数必须是纯ID字符串,不能传入XPath格式的表达式 - 你写的
//*[@id=question]是XPath语法,但搭配了id定位方式,直接导致语法冲突
另外你的XPath表达式本身也存在错误:属性值必须用引号包裹,正确写法应为//*[@id="question"]
以下是两种修正后的可行代码:
方法1:用ID定位(推荐,执行效率更高)
driver.implicitly_wait(2) question = driver.find_element('id', 'question') question.get_attribute('value')
方法2:用XPath定位
driver.implicitly_wait(2) question = driver.find_element('xpath', '//*[@id="question"]') question.get_attribute('value')
内容的提问来源于stack exchange,提问作者Louis Griffiths
相关产品推荐
相关产品推荐

