【问题标题】:How to write xpath with same class but different index?如何编写具有相同类但不同索引的xpath?
【发布时间】:2016-05-17 02:47:15
【问题描述】:

我想获得第二个具有相同班级的人。里面有链接。

<ul>
    <li class="arrow">
        <a href="somelinks.com"> </a>
    </li>
    <li></li>
    <li></li>
    <li class="arrow">
        <a href="someotherlinkstopage.com"> </a>
    </li>
    <li></li>
</ul>

我想获得“someotherlinkstopage.com”。这是倒数第二个里。我应该试试倒数第二个吗?还是去上课?

我试过了:

//(li[contains(@class,'arrow'])[2]/a/@href

//li[contains(@class, 'arrow')][2]/a/@href

//li[@class='arrow'][2]/a/@href

【问题讨论】:

    标签: xpath


    【解决方案1】:

    你们很亲密。以下 XPath,

    (//li[@class = 'arrow'])[2]/a/@href
    

    将根据要求选择"someotherlinkstopage.com"

    在这种情况下,您也可以使用contains(),但要注意与arrowssparrow 等匹配。请参阅How can I select an element with multiple classes with Xpath?

    【讨论】:

    • 您的第二次和第三次尝试以及我提供的解决方案将适用于您显示的示例 HTML。如果您使用我或您的后两个解决方案没有成功,那么您没有提供有代表性的 HTML 摘录。
    • 我检查了 html.. 只包含两个“箭头”.. 我真的不知道为什么.. 在此之前我没有意识到它有 2 个“箭头”,我编码 //li[contains(@ class, 'arrow')]/a/@href ,它转到第二页然后它停止了.. 但它刮掉了第一页和第二页..
    • 应该去“第二”最后一个吗?最后一个()-1?
    【解决方案2】:

    我已经使用

    解决了这个问题
    (//li[@class='arrow'])[last()]/a/@href
    

    我不知道为什么 [2] 不能使用但 last() 可以..

    但我知道我使用 last() 因为只有 2 个名为箭头的类.. 第一个或最后一个。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多