我以前使用 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>]
关于python - XPath 使用 lxml 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6778840/