【问题标题】:How to get the highest page number using xpath?如何使用 xpath 获取最高页码?
【发布时间】:2018-04-18 10:42:17
【问题描述】:

我编写了一个 xpath 表达式来从一些 html elements 中获取 page number 的最大值。但是,使用下面的 xpath,我得到了最后一个文本,在这种情况下是 Next Page。我希望我的 xpath 以这样的方式运行,以便我可以获得最高的数字,就像在 6 中使用它一样。

应应用 xpath 的元素:

content = """
<div class="nav-links"><span aria-current="page" class="page-numbers current"><span class="meta-nav screen-reader-text">Page </span>1</span>
<a class="page-numbers" href="https://page/2/"><span class="meta-nav screen-reader-text">Page </span>2</a>
<span class="page-numbers dots">…</span>
<a class="page-numbers" href="https://page/6/"><span class="meta-nav screen-reader-text">Page </span>6</a>
<a class="next page-numbers" href="https://page/2/"><span class="screen-reader-text">Next Page</span></a></div>
"""

到目前为止我已经尝试过:

from lxml.html import fromstring

root = fromstring(above_content)
pagenum = root.xpath("//*[contains(@class,'page-numbers')][last()]/span")[0].text
print(pagenum)

我的输出:

Next Page

我希望得到的输出:

6

【问题讨论】:

    标签: python python-3.x xpath lxml


    【解决方案1】:

    您可以使用确切的类名来避免获取下一个链接:

    //a[@class="page-numbers"][last()]
    

    请注意,contains(@class,'page-numbers') 将返回带有数字和 Next 的链接,而 @class="page-numbers" 仅返回数字

    【讨论】:

    • 您的解决方案永远不会失败@sir Andersson。是的,它做到了。非常感谢。
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多