Skip to main content
 首页 » 编程设计

python之XPath 使用 lxml 失败

2025年05月04日10telwanggs

我以前使用 xpaths 对 HTML 和 XML 都取得了很好的效果,但这次似乎无法得到任何结果。

数据来自http://www.ahrefs.com/api/ ,在“答案示例”下,保存到 .xml 文件

我的代码:

from lxml import etree 
doc = etree.XML(open('example.xml').read()) 
print doc.xpath('//result') 

没有给出任何结果。

我哪里错了?

请您参考如下方法:

你需要拿namespace文档的考虑因素:

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