如何修复'AttributeError:'NoneType'对象没有属性'text'

时间:2019-05-21 16:01:48

标签: python web-scraping beautifulsoup

我是网络爬虫的新手,我正试图从 https://www.theweathernetwork.com/ca/hourly-weather-forecast/ontario/markham

我尝试使用soup.find刮取值,但是,我不确定参数是否正确。我正在尝试从下面的代码中获取值17:

<div class="info">
<div class="temp">17</div>
<div class="stackunits">
<div>
<span class="unitwrap">°C</span>
</div>
<div class="feels-like">
<span class="label">Feels like</span>
<span class="value">17</span>
</div>
</div>
</div>

# import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup

# specify url
quote_page = 'https://www.theweathernetwork.com/ca/hourly-weather-forecast/ontario/markham'

# query website and return html to the variable 'page'
page = urlopen(quote_page)

# parse html using BeautifulSoup and store in variable 'soup'
soup = BeautifulSoup(page, 'html.parser')

# take out the <div> of temp and get its value
atemp_box = soup.find('div', attrs={'class':'temp'})
atemp = atemp_box.text
print(atemp)
  

AttributeError:'NoneType'对象没有属性'text'

1 个答案:

答案 0 :(得分:0)

使用相同的端点(API),页面正在使用该端点获取该信息

import requests

r = requests.get('https://www.theweathernetwork.com/api/data/caon0409/hourly/cm?ts=1632').json()

然后是温度

r['obs']['t']

返回了很多信息。探索响应here。例如,您可以在以下位置找到短期预测:

r['sterm']['periods']