的XML的格式如下Python脚本,从一个网址动态读取XML数据(例如http://www.wrh.noaa.gov/mesowest/getobextXml.php?sid=KCQT&num=72):
<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文件中表示的格式。谢谢。 – WandaW
“没有工作”......你得到了什么错误?它应该已经炸掉了,只是解析文件。改为使用'ET.fromstring(weatherXML.text)'。 –