python - XPath 使用 lxml 失败

标签 python xml lxml

我以前使用 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/

相关文章:

Python BeautifulSoup 错误

python - 使用 lxml 在另一个元素之后追加元素

python - Django rest_auth.registration 即使在成功注册时也会发回错误

python - Pytest 不在终端窗口中显示测试结果

SQL 从包含 xml 的 nvarchar 列中透视动态列

xml - 如何在 XPath 中执行不区分大小写的搜索?

c# - XmllSerializer.Serialize 并返回原始 xml

python - 在保留属性的同时使用 lxml.objectify 替换节点文本

python - PyUnit 拆解和设置与 __init__ 和 __del__

python - GAE 中的 "soft private memory limit"是什么?