【问题标题】:invalid selector: The result of the xpath expression "//a[contains(@href, 'mailto')]/@href" is: [object Attr] getting the href attribute with Selenium无效的选择器:xpath 表达式 "//a[contains(@href, 'mailto')]/@href" 的结果是:[object Attr] 使用 Selenium 获取 href 属性
【发布时间】:2021-12-27 22:30:48
【问题描述】:

我目前正在尝试执行这个命令,尝试选择:

driver.find_element_by_xpath("//a[contains(@href, 'mailto')]/@href").getAttribute("href") 

<a href="X">时得到X。

它显示了这个错误:

invalid selector: The result of the xpath expression "//a[contains(@href, 'mailto')]/@href" is: [object Attr]. It should be an element.

我尝试过 .getAttribute 但没有成功。谁能帮我解决这个问题?

谢谢

【问题讨论】:

  • 始终将代码和标记添加为文本,并将其格式化为代码。无法轻松搜索或复制和粘贴图像以验证解决方案。谢谢。

标签: python selenium xpath css-selectors getattribute


【解决方案1】:

当您使用find_element_by_xpath 时,您应该提供一个选择元素而不是选择属性的 XPath 表达式。

所以放弃最后的/@href

【讨论】:

    【解决方案2】:

    此错误消息...

    invalid selector: The result of the xpath expression "//a[contains(@href, 'mailto')]/@href" is: [object Attr]. It should be an element.
    

    ...暗示 xpath 表达式 "//a[contains(@href, 'mailto')]/@href" 是无效表达式,因为它返回一个对象 attribute,而 Selenium 期望 WebElement

    一个快速的解决方案是从 xpath 的 fag 端删除 /@href 部分。


    综合解决方案

    要打印 href 属性的值,您可以使用以下任一Locator Strategies

    • 使用css_selector

      print(driver.find_element_by_css_selector("a.[href*='mailto']").get_attribute("href"))
      
    • 使用xpath

      print(driver.find_element_by_xpath("//a[starts-with(@href, 'mailto')]").get_attribute("href"))
      

    理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "//a[starts-with(@href, 'mailto')]"))).get_attribute("value"))
      
    • 使用XPATH

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='name' and @title='Download']"))).get_attribute("value"))
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2011-06-10
      • 2011-12-06
      • 2021-12-22
      • 2011-04-18
      • 2012-02-09
      相关资源
      最近更新 更多