使用XPath获取特定属性值
从下面这段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']