python 使用 XPath 获取特定属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2243131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:09:20  来源:igfitidea点击:

Getting certain attribute value using XPath

pythonxpath

提问by khelll

From the following HTML snippet:

来自以下 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" />

I'm trying to get the hrefvalue of the linktag with rel value = "shortcut icon", I'm trying to achieve that using XPath.

我试图获得href的价值link与相对价值标签= "shortcut icon",我试图做到这一点使用XPath。

How to do that in Python?

如何在 Python 中做到这一点?

回答by MattH

Like this:

像这样:

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']