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

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

问题描述:

我是python和xml的新手。我试图从airnow.gov网站获取空气质量指数数据。我使用感应自动化的点火软件来显示这些信息。当我为天气做这件事时,我使用的*网站的数据容易解析。使用xml在Python中解析数据airnow.gov

虽然这不是那么简单。我的输出包含了第二个描述元素的所有内容,其中包含我真正需要的唯一数据 - 空气质量指数。这就像是跳过剩余的数据。

任何帮助,将不胜感激!


我的代码:

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 

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> 
[email protected] (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 
[email protected] (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 
+0

的第一个子节点'description'是注释。你想要第二个孩子。例如:'tag = dom.getElementsByTagName(“description”)[1] print(tag.childNodes [2] .data)' –

首先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, CASan Francisco, CA Location: