繁体   English   中英

XPath - 获取属性“href”

[英]XPath - get attribute “href”

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

<td>
    <a href="http://www.stackoverflow.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.stackoverflow.com

您的 XPath 部分适用于我的

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

您正在使用哪些工具,您期望的 output 是什么,而您得到的是什么?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM