XML到CSV合作项目

2024-10-03 19:23:09 发布

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

现在我在工作中发现了一个问题。 我需要来自http://air4thai.pcd.go.th/services/getAQI_XML.php?region=2的XML数据 我想解析XML并输出到CSV

我是python的新手 现在我测试编码解析PM10像这样

import xml.etree.ElementTree as ET
import requests
import os
Air4thaiURL = 'http://air4thai.pcd.go.th/services/getAQI_XML.php?region=2'
resp = requests.get(Air4thaiURL)
msg = resp.content
tree = ET.fromstring(msg)
for station in tree.findall('.//station/LastUpdate'):
print ('{}'.format(
station.get('PM10')))   

但结果是这样的

没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有 没有

所以,它必须显示在Value/Im中,并尝试键入:s it's result

Traceback (most recent call last):
  File "C:\Users\Gistda59\Desktop\Coop - Python Script\pm10_XML.py", line 11, in <module>
    station.get('PM10')))
TypeError: non-empty format string passed to object.__format__

如何解决这个问题,并建议我从这个URL解析XML到CSV 非常感谢你帮我解决问题。你知道吗


Tags: importformathttpgogetservicexmlregion
1条回答
网友
1楼 · 发布于 2024-10-03 19:23:09

这就是你想要的:

import xml.etree.ElementTree as ET
import requests
import os
Air4thaiURL = 'http://air4thai.pcd.go.th/services/getAQI_XML.php?region=2'
resp = requests.get(Air4thaiURL)
msg = resp.content
tree = ET.fromstring(msg)
for station in tree.findall('.//station/LastUpdate'):
    if station.tag == 'LastUpdate':
        for item in station:
            if item.tag == 'PM10':
                print(item.attrib)

相关问题 更多 >