使用XPath获取特定属性值

12 投票
1 回答
25245 浏览
提问于 2025-04-15 19:08

从下面这段HTML代码开始:

<link rel="index" href="/index.php" />
<link rel="contents" href="/getdata.php" />
<link rel="copyright" href="/blabla.php" />
<link rel="shortcut icon" href="/img/all/favicon.ico" />

我想获取一个link标签的href值,这个标签的rel属性值是"shortcut icon"。我想用XPath来实现这个目标。

请问在Python中怎么做呢?

1 个回答

22

像这样:

data = """<link rel="index" href="/index.php" />
<link rel="contents" href="/getdata.php" />
<link rel="copyright" href="/blabla.php" />
<link rel="shortcut icon" href="/img/all/favicon.ico" />
"""

from lxml import etree

d = etree.HTML(data)

d.xpath('//link[@rel="shortcut icon"]/@href')
['/img/all/favicon.ico']

撰写回答