【发布时间】:2018-03-16 13:38:41
【问题描述】:
我正在尝试编写一个从 URL 动态读取 XML 数据的 Python 脚本(例如http://www.wrh.noaa.gov/mesowest/getobextXml.php?sid=KCQT&num=72)
XML格式如下:
<station id="KCQT" name="Los Angeles / USC Campus Downtown" elev="179" lat="34.02355" lon="-118.29122" provider="NWS/FAA">
<ob time="04 Oct 7:10 pm" utime="1507169400">
<variable var="T" description="Temp" unit="F" value="61"/>
<variable var="TD" description="Dewp" unit="F" value="39"/>
<variable var="RH" description="Relh" unit="%" value="45"/>
</ob>
<ob time="04 Oct 7:05 pm" utime="1507169100">
<variable var="T" description="Temp" unit="F" value="61"/>
<variable var="TD" description="Dewp" unit="F" value="39"/>
<variable var="RH" description="Relh" unit="%" value="45"/>
</ob>
<ob time="04 Oct 7:00 pm" utime="1507168800">
<variable var="T" description="Temp" unit="F" value="61"/>
<variable var="TD" description="Dewp" unit="F" value="39"/>
<variable var="RH" description="Relh" unit="%" value="45"/>
</ob>
<ob time="04 Oct 6:55 pm" utime="1507168500">
<variable var="T" description="Temp" unit="F" value="61"/>
<variable var="TD" description="Dewp" unit="F" value="39"/>
<variable var="RH" description="Relh" unit="%" value="45"/>
</ob>
</station>
我只想检索所有可用日期的时间戳和十进制温度(“Temp”)(我包含的日期不止 4 个)。
输出应为 CSV 格式的文本文件,其中时间戳和温度值每行打印一对。
以下是我对代码的尝试(这很糟糕,根本不起作用):
import requests
weatherXML = requests.get("http://www.wrh.noaa.gov/mesowest/getobextXml.php?sid=KCQT&num=72")
import xml.etree.ElementTree as ET
import csv
tree = ET.parse(weatherXML)
root = tree.getroot()
# open file for writing
Time_Temp = open('timestamp_temp.csv', 'w')
#csv writer object
csvwriter = csv.writer(Time_Temp)
time_temp = []
count = 0
for member in root.findall('ob'):
if count == 0:
temperature = member.find('T').var
time_temp.append(temperature)
csvwriter.writerow(time_temp)
count = count + 1
temperature = member.find('T').text
time_temp.append(temperature)
Time_Temp.close()
请帮忙。
【问题讨论】:
-
我看不到 xml 文件中的“年、月、日、分、秒和时区偏移量”是如何表示的。
-
@BillBell 对此感到抱歉,我已经编辑了要求。时间戳现在将遵循 xml 文件中表示的格式。谢谢。
-
“没有工作”...您遇到了什么错误?它应该只是解析文件就爆炸了。请改用
ET.fromstring(weatherXML.text)。
标签: python xml csv xml-parsing elementtree