2017-10-12 39 views
0

我是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)' –

回答

0

首先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: