2011-07-21 90 views
2

我以前使用xpaths對HTML和XML都有很好的效果,但這次似乎無法獲得任何結果。XPath使用lxml失敗

的數據是從http://www.ahrefs.com/api/,在「答案示例」,保存到一個.xml文件

我的代碼:

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

不給出任何結果。

我哪裏錯了?

回答

1

你需要採取文件的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>] 
0

我的經驗是在C#中使用XPath,但我相信XML命名空間導致您的查詢失敗。您需要使用local()運算符的一些變體,或者查看您的文檔,以便事先定義名稱空間。