【问题标题】:InvalidSelectorException: Message: invalid selector: The result of the xpath expression is [object Attr]. It should be an element using XPath SeleniumInvalidSelectorException:消息:无效选择器:xpath 表达式的结果是 [object Attr]。它应该是使用 XPath Selenium 的元素
【发布时间】:2020-06-21 19:29:54
【问题描述】:

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

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.

我该如何解决这个问题?

【问题讨论】:

  • 当您有文本输出时,don't take a picture but copy paste the output in your POST 也可以从浏览器控制台中复制 html:从检查器中,右键单击 -> 复制为 outerHTML。
  • 您不能选择属性节点,它们不是作为单独的对象实现的。选择 <a> 元素本身,然后使用 Python 代码获取属性值。
  • 我不是在我的代码中选择了<a> 吗?

标签: python-3.x selenium selenium-webdriver xpath webdriver


【解决方案1】:

此错误消息...

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 表达式


记录在案 Selenium WebDriver 仅支持 xpath-1.0,它返回由 xpath 选择的节点集。

您可以在XML Path Language (XPath) Version 1.0 中找到 规范

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

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

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

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

您可以在XML Path Language (XPath) 2.0 (Second Edition) 中找到 规范


解决方案

要根据 ST 的以下兄弟输入值来定位具有 href 属性的所需元素,该属性连接到名为“John Doe”的学生,您可以使用以下 基于Locator Strategies

  • 使用前置

    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()
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2021-04-05
    • 2019-08-07
    • 1970-01-01
    • 2018-09-29
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多