InvalidSelectorException:消息:无效的选择器:xpath 表达式的结果是 [object Attr]。它应该是一个使用 XPath Selenium 的元素

InvalidSelectorException: Message: invalid selector: The result of the xpath expression is [object Attr]. It should be an element using XPath Selenium

您好,我想根据 'ST' 的 following-sibling 输入值定位连接到名为“John Doe”的学生的 href 元素。这是我用于 select 元素的代码:

driver.find_element_by_xpath('//a[following-sibling::input[@value="ST"]]/@href').click()

它正在定位正确的元素,但我收到此错误:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//a[following-sibling::input[@value="ST"]]/@href" is: [object Attr]. It should be an element.

我该如何解决这个问题?

这个错误信息...

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//a[following-sibling::input[@value="ST"]]/@href" is: [object Attr]. It should be an element.

......暗示您的 XPath 表达式不是有效的 xpath 表达式.


备案 仅支持 xpath-1.0 return 由 xpath 选择的节点集。

You can find the specifications in XML Path Language (XPath) Version 1.0

您使用的 xpath 表达式在哪里:

driver.find_element_by_xpath('//a[following-sibling::input[@value="ST"]]/@href')

是一个基于 xpath-2.0 的表达式,通常 return 一个 object Attr。几个例子:

  • //@version:选择与上下文节点在同一个文档中的所有版本属性节点
  • ../@lang:选择上下文节点父级的lang属性

You can find the specifications in XML Path Language (XPath) 2.0 (Second Edition)


解决方案

根据 ST[= 的以下同级输入值,使用连接到名为“John Doe”的学生的 href 属性定位所需元素67=] 您可以使用以下任一项 based :

  • 使用前面:

    driver.find_element_by_xpath("//input[@value='ST']//preceding::a[1]").click()
    
  • 使用 preceding-sibling:

    driver.find_element_by_xpath("//input[@value='ST']//preceding-sibling::a[@href]").click()