【问题标题】:how to get the penultimate element?如何获得倒数第二个元素?
【发布时间】:2014-03-10 10:47:45
【问题描述】:

请帮助使用 xpath 获取第二个标签的内容。下面是我写的代码。但它不起作用

import lxml.html

doc = lxml.html.document_fromstring("""
    <nav class="Paging">
            <a href="/women/dresses/cat/4?page=1" class="active">1</a>
            <a href="/women/dresses/cat/4?page=2">2</a>
            <a href="/women/dresses/cat/4?page=2" rel="next">Next »</a>
    </nav>
""")
res = doc.xpath('//nav[@class="Paging"][position() = 1]/a[position() = last() and @rel != "next"]/text()')

print(res)

【问题讨论】:

    标签: python xpath lxml


    【解决方案1】:

    您当前的表达式不起作用,因为a[position() = last() and @rel != "next"] 尝试匹配最后一个元素如果rel 属性与"next" 不同。您的标记中不是这种情况,因此表达式不匹配任何内容。

    您可以将position()last() - 1 进行比较:

    res = doc.xpath('//nav[@class = "Paging" and position() = 1]'
        + '/a[position() = last() - 1]/text()')
    

    【讨论】:

    【解决方案2】:

    你可以试试xpath:

    //nav[@class="Paging"][position() = 1]/a[position() = last() - 1][not(@rel)]/text()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 2020-11-12
      相关资源
      最近更新 更多