我正在运行以下代码,以便从页面中抓取价格,但我一直得到这个错误。最初我尝试只是添加内部类attrs{},然后我尝试包括类,它是在但两次我得到了相同的错误。我不认为url有问题,因为当我运行webbrowser.open(url)
时,它工作了。此外,print(soup.prettify())
确实给了我页面的内容,所以我怀疑那里有问题。我该怎么办?
def getCurrentPrice(cc): #Scraping the current price of the cryptocurrency from the web
url = 'https://www.google.com/search?q='+cc+'+price+euros'
#webbrowser.open(url)
HTML=requests.get(url)
soup=BeautifulSoup(HTML.text, 'html.parser')
#print(soup.prettify())
text=soup.find('div', attrs= {'class': 'card-section PZPZlf'}).find('div', attrs={'class': 'pclqee'}).text
print('Current Price: '+text+'EUR')
return text
line 47, in getCurrentPrice
text=soup.find('div', attrs= {'class': 'card-section PZPZlf'}).find('div', attrs={'class': 'pclqee'}).text
AttributeError: 'NoneType' object has no attribute 'find'
我想是因为soup.find()
可以返回None
修复:
def getCurrentPrice(cc): #Scraping the current price of the cryptocurrency from the web
"""Function that get the current price. Can return None"""
url = 'https://www.google.com/search?q='+cc+'+price+euros'
#webbrowser.open(url)
HTML=requests.get(url)
soup=BeautifulSoup(HTML.text, 'html.parser')
#print(soup.prettify())
text=soup.find('div', attrs= {'class': 'card-section PZPZlf'})
if text is not None:
text = text.find('div', attrs={'class': 'pclqee'})
else:
return
if text is not None:
text = text.text
else:
return
print('Current Price: '+text+'EUR')
return text
这个函数可以返回None。