尝试直接从URL解析XML

2024-10-01 04:49:17 发布

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

我在看这个XML:

https://data.cityofnewyork.us/api/views/25th-nujf/rows.xml

我以为我可以用下面的代码从列表中解析出“ethcty”和“cnt”项,但实际上我什么都没有得到。在

import xml.etree.ElementTree as ET
tree = ET.parse('https://data.cityofnewyork.us/api/views/25th-nujf/rows.xml')
root = tree.getroot()

for child in root:
    print(child.tag, child.attrib)

for _id in root.findall('_id'):
    rank = _id.find('ethcty').text
    name = _id.get('cnt')
    print(name, rank)

我下面的例子来自下面的网址。在

https://docs.python.org/3.4/library/xml.etree.elementtree.html


Tags: httpsapiidchilddatarootxmlviews
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:17

response元素中有一个row元素,因此for循环应该在root[0]中,而不是{}

下面是一个例子,希望它能帮助你理解这个问题

import xml.etree.ElementTree as ET
tree = ET.parse('rows.xml')
root = tree.getroot()

for _id in root[0].findall('row'):
    rank = _id.find('ethcty').text
    name = _id.find('cnt').text
    print(name, rank)

另外,findall应该是所需节点的名称

至于直接从url加载,您应该使用urllib,如下所示:

^{pr2}$

我编辑了后一个代码,因为我忘记了从URL加载问题的部分,对此我很抱歉

相关问题 更多 >