如何得到解决属性错误时,网页抓取谷歌风速



我正在抓取谷歌的风速,直到几周前,这段代码工作得很好!现在我运行它,我一直得到一个"AttributeError: 'NoneType'对象没有属性'text'"错误。我可以做些什么来让它像以前一样工作?我很困惑为什么它停止工作了!

import requests
import re
from bs4 import BeautifulSoup as bs
#Function that returns windpseed in a dictionary
def current_windspeed(url):
#Defining user agent and language to scrape google
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
#Setting language as UK english
LANGUAGE = "en-UK,en;q=0.5"
session=requests.Session()
session.headers['User-Agent']= USER_AGENT
session.headers['Accept-Language']= LANGUAGE
session.headers['Content-Language']=LANGUAGE
#downloads html code for google weather london
html=session.get(url)
#creates a new soup
soup=bs(html.text, "html.parser")
#dictionary where windspeed will be stored
current_weather={}
print(current_weather)
current_weather['wind']=soup.find("span",attrs={"id": "wob_ws"}).text
return current_weather

它标记的问题是这行代码

current_weather['wind']=soup.find("span",attrs={"id": "wob_ws"}).text

我到底要怎么让它重新工作,为什么它停止工作了?

解析假设您一直从服务器返回良好的数据。我每天24小时加载天气数据,它可以持续许多天甚至几周,但服务器偶尔会给你一个404或空文件或其他罕见的情况。

位码:

soup.find("span",attrs={"id": "wob_ws"})

没有找到任何东西,所以返回None。

您的代码可以编写为优雅地接受错误输入,并在记录问题的同时继续。你通常可以假设它会在以后自行修复,并使用try/except,记录错误并在下一次获得它。如果服务器更改了网页,那么您可能需要重新编写代码。

最新更新