Matt
Matt

Reputation: 33

XPath failing using lxml

I have used xpaths to great effect with both HTML and XML before, but can't seem to get any results this time.

The data is from http://www.ahrefs.com/api/, under "Example of an answer", saved to an .xml file

My code:

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

which doesn't give any results.

Where am I going wrong?

Upvotes: 2

Views: 498

Answers (2)

mzjn
mzjn

Reputation: 50937

You need to take the namespace of the document into account:

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

Upvotes: 1

horatius83
horatius83

Reputation: 393

My experience is from using XPath in C#, but I believe the XML namespace is causing your query to fail. You'll need to either use some variation of the local() operator, or check your documentation for some way of defining the namespace beforehand.

Upvotes: 0

Related Questions