在 python 中使用 XPath 提取包含关键字的 href 值

extract href values containing keyword using XPath in python

我知道这个问题的变体已被问过很多次,但我无法破解它并得到我想要的。

我有一个 website,里面有几个 table。感兴趣的 table 包含一列,其中每一行都包含超链接到不同页面的单词 Text。这是上面链接页面第一行的具体示例:

<a href="_alexandria_RIC_VI_099b_K-AP.txt">Text</a>

这是一般模式:

<a href="_something_something-blah-blah.txt">Text</a>

现在我正在这样做:

import requests  
import lxml.html as lh
page = requests.get("http://www.wildwinds.com/coins/ric/constantine/t.html")
doc = lh.fromstring(page.content)
href_elements = doc.xpath('/html/body/center/table/tbody/tr/td/a/@href')
print(href_elements)

所需的响应应该是一个如下所示的项目数组:_something_something-blah-blah.txt我得到的是一个空数组。

由于该页面有其他我不感兴趣的 href 元素,我还想修改查询以仅获取其值中包含 .txt 的 href 元素。

非常感谢您提供的任何帮助!

试试这样的东西:

href_elements = doc.xpath('//center//table//a[contains(@href,".txt")]["Text"]/@href')
for href in href_elements:
    print(href)

输出:

_alexandria_RIC_VI_099b_K-AP.txt
_alexandria_RIC_VI_100.txt
_alexandria_RIC_VI_136.txt
_alexandria_RIC_VI_156.txt

等等