我编写了一个 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/