【问题标题】:What is the XPath for the following element?以下元素的 XPath 是什么?
【发布时间】:2019-07-05 00:50:12
【问题描述】:

我需要找到以下元素的 XPath:

<a> href="/resident/register/">Register another device </a>

我认为解决方案是

$x("//*[contains(@href, 'resident/register')]")

但这并没有返回任何东西。有什么想法吗?

【问题讨论】:

  • “有什么想法吗?”您可能需要检查:xpath-syntax.
  • 这取决于页面的其余部分是如何构建的。不管怎样,Firefox can tell you
  • 嗨@Sam1811x,试试这个//a[text()='Register another device']定位器
  • 请注意,没有元素的“the”XPath 之类的东西。您通常会希望选择一个 XPath 表达式,该表达式在文档中唯一标识元素,并且在文档发生微小更改时保持稳定。因此,XPath 的最佳选择非常依赖于上下文。但是你失败的原因似乎是 href 实际上不是一个属性,它似乎是输入错误的。

标签: python html xml selenium xpath


【解决方案1】:

您的 HTML 格式不正确。

改变

<a> href="/resident/register/">Register another device </a>

<a href="/resident/register/">Register another device </a>

那么您的 XPath 将按预期工作。

如果您的 HTML 是固定的,那么您将不得不调整您的 XPath 以测试元素内容而不是 href 属性内容:

//a[contains(.,'resident/register')]

但是,虽然这可以选择格式错误的 a 元素,但由于缺少正确的 href 属性,因此无法单击它。

【讨论】:

    【解决方案2】:

    首先@kjhughes 指出了 HTML 的问题之一,即 HTML 格式错误,因为您必须尝试根据自己的理解提供正确的 HTML。

    我想实际的HTML如下:

    <a href="/resident/register/">Register another device </a>
    

    因此,元素的有效 XPath 可以是以下任意一种:

    • XPath:1

      "//a[contains(@href, '/resident/register') and contains(.,'Register another device')]"
      
    • XPath:2

      "//a[contains(@href, '/resident/register') and normalize-space()='Register another device']"
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 2017-02-24
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      相关资源
      最近更新 更多