使用lxml、python获取最后一个(最新)元素

2024-04-25 19:51:20 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,在过去的几天里,我得到了一些惊人的帮助,试图解决我的问题。我只想问最后一个问题(我希望):

我试图从xml中获取最后一个元素并将其放入变量中。我使用的是django、python和lxml库。在

我想做的是,浏览从API调用中得到的XML,找到最新的项目(它将具有最大的ID号),然后将其分配给一个变量以存储在我的数据库中。我很难找到最新的元素。在

下面是一个代码片段:

req2 = urllib2.Request("http://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)
        #assigns the api_id to the id at index of 0 for time being,  using the // in front of project makes sure that its looking at the correct node inside of the projects structure
        api_id = int(data.xpath('//project/id/text()')[0])
        project.API_id = api_id
        project.save()

目前,它接受位于[0]的元素并存储ID,但是我需要最新的/newst/etc元素。在

谢谢

史蒂夫


Tags: oftheprojectapiid元素dataxml
1条回答
网友
1楼 · 发布于 2024-04-25 19:51:20

[0]更改为[-1],以选择列表中最后一个元素:

api_id = int(data.xpath('//project/id/text()')[-1])

请注意,如果最大值不在列表的末尾,这可能不会给出最大值id值。在

要获得最大的id,可以执行以下操作:

^{pr2}$

相关问题 更多 >