python - 如何使用xpath获取最高页码?

标签 python python-3.x xpath lxml

我编写了一个 xpath 表达式来从某些 html 元素 获取页码 的最高值。然而,通过下面的 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

最佳答案

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

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

请注意,contains(@class,'page-numbers') 将返回包含数字和“下一页”的链接,而 @class="page-numbers" 仅返回数字

关于python - 如何使用xpath获取最高页码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897682/

相关文章:

python - 将 cookie 加载到 Python 请求 session 时出错

Python 在线程中获取/发布数据

python-3.x - Python 3.7、Ubuntu 16.04 中的 Celery 任务未注册异常

python - 从 "[YYYY]-[MM]-[DD]T[HH]:[MM]:[SS]+[XXXX]"转换为 unix 时间戳

Python Turtle - 无法为 turtle 设置边界?

python-2.7 - 构造Xpath

python - 属性错误 : 'function' object has no attribute 'upper'

python - Django NoReverseMatch : Reverse not found, 不是有效的 View 函数或模式名称

python - 如何将xml xpath解析为列表python

c# - 如何使用C#获取XML中特定属性的值?