XPath - 获取属性 "href"

XPath - get attribute "href"

如何使用 XPath 从 html 获取“href”属性?

<td>
    <a href="http://www.whosebug.com">
       <p>SERVER-45472</p>
    </a>
</td>

为什么对我来说只能使用“//a/@href”这个命令? 为什么我不能使用此查询 - “/td//a/@href”?

我想做什么:

from lxml import html

tree = html.fromstring('<td><a href="https://jira.mongodb.org/browse/SERVER-45472"><p>SERVER-45472</p></a></td>')

a = tree.xpath('/td//a/@href')
print(a)

在运行脚本之后,一个空列表返回给我

像这样的 XPath :

string(//a/@href)
http://www.whosebug.com

你的 XPath 部分适用于我 :

xmllint --xpath '/td//a/@href' file
href="http://www.whosebug.com"

您正在使用哪些工具,您的预期输出是什么,而您得到的是什么?

因为 HTML 文件的一部分不是有效的 HTML 文档。

参见:

$ python
Python 2.7.16 (default, Oct 10 2019, 22:02:15) 
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import html
>>> tree = html.fromstring('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html>  <body><td><a href="https://jira.mongodb.org/browse/SERVER-45472"><p>SERVER-45472</p></a></td></body></html>')
>>> a = tree.xpath('/html/body/td//a/@href')
>>> print(a)
['https://jira.mongodb.org/browse/SERVER-45472']
>>>