[英]XPath failing using lxml
我之前在 HTML 和 XML 上都使用过 xpath,效果很好,但这次似乎没有得到任何结果。
数据来自http://www.ahrefs.com/api/ ,在“答案示例”下,保存到 .xml 文件
我的代码:
from lxml import etree
doc = etree.XML(open('example.xml').read())
print doc.xpath('//result')
这没有给出任何结果。
我哪里错了?
您需要考虑文档的命名空间:
from lxml import etree
doc = etree.parse('example.xml')
print doc.xpath('//n:result',
namespaces={'n': "http://ahrefs.com/schemas/api/links/1"})
=>
[<Element {http://ahrefs.com/schemas/api/links/1}result at 0xc8d670>,
<Element {http://ahrefs.com/schemas/api/links/1}result at 0xc8d698>]
我的经验是在 C# 中使用 XPath,但我相信 XML 命名空间会导致您的查询失败。 您需要使用 local() 运算符的一些变体,或者检查您的文档以了解预先定义命名空间的某种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.