在Python中使用xml airnow.g解析数据

2024-04-24 23:12:47 发布

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

我不熟悉python和xml。我想从卫星上获取空气质量指数数据airnow.gov网站网站。我用感应自动化的点火软件来显示这个信息。当我为天气做这项工作时,我使用的政府网站的数据格式很容易解析。你知道吗

不过,这个并不是那么简单。我的输出包含了第二个description元素之前的所有内容,其中包含了我真正需要的唯一数据——空气质量指数。就像跳过了剩下的数据。你知道吗

任何帮助都将不胜感激!你知道吗


我的代码:

import system
import xml.dom.minidom

url = "http://feeds.enviroflash.info/rss/realtime/133.xml"

response = system.net.httpGet(url)

dom = xml.dom.minidom.parseString(response)

for tag in dom.getElementsByTagName("*"):
print tag.firstChild.data

数据:

<rss version="2.0">
<channel>
<title>San Francisco, CA - Current Air Quality</title>
<link>http://www.airnow.gov/</link>
<description>EnviroFlash RSS Feed</description>
<language>en-us</language>
<webMaster>
airnowdmc@sonomatech.com (AIRNow Data Management Center)
</webMaster>
<pubDate>Thu, 12 Oct 2017 08:45:10 PDT</pubDate>
<item>
<title>San Francisco, CA - Current Air Quality</title>
<link>
http://feeds.enviroflash.info/rss/realtime/133.xml?id=AC9AF12B-02F4-5A9E-BD504999C6EF606E
</link>
<description>
<!--  Format data output  -->
 <div xmlns="http://www.w3.org/1999/xhtml"> <table style="width: 350px;">    
 <tr> <td> <br> </td> </tr> <tr> <td valign="top">
 <div><b>Location:</b> San Francisco, CA</div><br /> <div> <b>Current
 Air Quality:</b> 10/12/17 8:00 AM PDT<br /><br /> <div> Unhealthy -
 156 AQI - Particle Pollution (2.5 microns)<br /> <br /> Good - 1 AQI -
 Ozone<br /> <br /> </div> </div> <div><b>Agency:</b> San Francisco Bay
 Area AQMD </div><br /> <div><i>Last Update: Thu, 12 Oct 2017 08:45:10
 PDT</i></div> </td> </tr> </table> </div>
</description>
</item>
</channel>
</rss>

我的输出:

San Francisco, CA - Current Air Quality
http://www.airnow.gov/
EnviroFlash RSS Feed
en-us
airnowdmc@sonomatech.com (AIRNow Data Management Center)
Thu, 12 Oct 2017 08:45:10 PDT


San Francisco, CA - Current Air Quality
http://feeds.enviroflash.info/rss/realtime/133.xml?id=AC9AF12B-02F4-5A9E-BD504999C6EF606E

Tags: 数据brdivhttptitledescriptionxmlcurrent
1条回答
网友
1楼 · 发布于 2024-04-24 23:12:47

第一个HTML不是XML。因此,请考虑使用BeautifulSoup来做同样的事情,以类似的方式。例如,<br>是一个有效的标记,在html中没有任何匹配的结束标记。但是xml解析器会抛出一个错误。你知道吗

那就是说你看下图:-你知道吗

#Will give you all text in the html, your codes attempt
for tag in dom.getElementsByTagName("*"):
    if tag.firstChild and not isinstance(tag.firstChild,xml.dom.minidom.Element) :
        if(len(tag.firstChild.data.strip())>0):
            print tag.firstChild.wholeText
print('\n\n\n')
#Will give you text from just the second description.
#I believe all parts here are important like time/place/last-update etc..
desc=dom.getElementsByTagName("description")[1]
for tag in desc.getElementsByTagName("*"):
    for node in tag.childNodes:
        if( isinstance(node,xml.dom.minidom.Text) and len(node.data.strip())>0):
            print node.data

希望你能想出如何得到Location: San Francisco, CA而不是San Francisco, CA Location:

相关问题 更多 >