I have a small issue. I am trying to pull some data from my XML using lxml and I keep getting a “list index out of range” error, now I am trying to get the [0] position of my list, which should be the first one but it keeps giving me the error.
Here is a code snippet (thanks to MattH for helping me out):
req2 = urllib2.Request("web_url/public/api.php?path_info=/projects&token=##############")
resp = urllib2.urlopen(req2)
resp_data = resp.read()
if not resp.code == 200 and resp.headers.get('content-type') == 'text/xml':
# Do your error handling.
raise Exception('Unexpected response',req2,resp)
data = etree.XML(resp_data)
api_id = int(data.xpath('/project/id/text()')[0])
project.API_id = api_id
project.save()
Now when I do a print statement, it pulls the XML so I know that I have xml data and its not blank, but not sure what else could be causing this?
Thanks!
Steve
With your XML document’s structure being
your XPath expression
/project/id/text()surely won’t match anything, and the accessing index 0 of the empty XPath result list of course results in anIndexError.Instead of
/project, which only matches a root (!) element called "project", you might want to use/projects/projector//project. So a correct XPath for your XML structure would be//project/id/text().