2013-07-21 91 views
0

我正在編寫腳本以從網頁收集天氣數據。我的代碼去如下:Python-無法使用BeautifulSoup查找CSS類

import urllib.request 
from bs4 import BeautifulSoup 

# open the webpage and assign the content to a new variable 
base = urllib.request.urlopen('http://www.weather.com/weather/today/Washington+DC+20006:4:US') 
f = base.readlines() 
f = str(f) 


soup = BeautifulSoup(f) 

rn_base = soup.find(itemprop="temperature-fahrenheit") 
right_now = rn_base.string 
print(right_now) 

fl_base = soup.find(itemprop="feels-like-temperature-fahrenheit") 
feels_like = fl_base.string 
print(feels_like) 

td_base = soup.find_all('class_="wx-temperature"') 
print(td_base) 

所以right_nowfeels_like印製精美,但是當涉及到td_base,它返回要麼None[],這取決於是否使用.find.find_all一個空列表。爲了解釋HTML源代碼,我的代碼能夠找到itemprop="temperature-fahrenheit"itemprop="feels-like-temperature-fahrenheit",但在class_="wx-temperature"上失敗。我很欣賞任何想法,爲什麼前兩個會成功,但不是第三個。謝謝!

P.S。:下面是HTML源代碼是相關(IMO)到手頭的任務的摘錄:

<div class="wx-data-part wx-first"> 
<div class="wx-temperature"><span itemprop="temperature-fahrenheit">87</span><span class="wx-degrees">&deg;<span class="wx-unit">F</span></span></div> 
<div class="wx-temperature-label">FEELS LIKE 
<span itemprop="feels-like-temperature-fahrenheit">93</span>&deg;</div> 
</div> 
<div class="wx-data-part"> 
<div class="wx-temperature">94<span class="wx-degrees">&deg;</span></div> 
<div class="wx-temperature-label">HIGH AT 3:25 PM</div> 
</div> 
<div class="wx-data-part"> 
<div class="wx-temperature">76<span class="wx-degrees">&deg;</span></div> 
<div class="wx-temperature-label">LOW</div> 
</div> 

回答

1

刪除周圍'

td_base = soup.find_all(class_="wx-temperature")