开发者

Using lxml & django/python - list index out of range

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])
        p开发者_如何学Pythonroject.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

<projects>
    <projects>
        <id>
            ...
        </id>
    </project>
</projects>

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 an IndexError.

Instead of /project, which only matches a root (!) element called "project", you might want to use /projects/project or //project. So a correct XPath for your XML structure would be //project/id/text().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜