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_now
和feels_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">°<span class="wx-unit">F</span></span></div>
<div class="wx-temperature-label">FEELS LIKE
<span itemprop="feels-like-temperature-fahrenheit">93</span>°</div>
</div>
<div class="wx-data-part">
<div class="wx-temperature">94<span class="wx-degrees">°</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">°</span></div>
<div class="wx-temperature-label">LOW</div>
</div>