'NoneType' 对象在 BeautifulSoup 中没有属性 'text' [英] 'NoneType' object has no attribute 'text' in BeautifulSoup
问题描述
当我搜索什么是 2+2"时,我试图抓取 Google 结果,但以下代码返回了 'NoneType' 对象没有属性 'text'
.请帮助我实现所需的目标.
I am trying to scrape Google results when I search "What is 2+2", but the following code is returning 'NoneType' object has no attribute 'text'
. Please help me in achieving the required goal.
text="What is 2+2"
search=text.replace(" ","+")
link="https://www.google.com/search?q="+search
headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}
source=requests.get(link,headers=headers).text
soup=BeautifulSoup(source,"html.parser")
answer=soup.find('span',id="cwos")
self.respond(answer.text)
唯一的问题是soup.find
中的id
,但是我非常谨慎地选择了这个id.我不应该弄错.我也试过 answer=soup.find('span',class_="cwcot gsrt")
,但都没有奏效.
The only problem is with id
in soup.find
, however I have chosen this id very closely. I shouldn't be mistaken. I also tried answer=soup.find('span',class_="cwcot gsrt")
, but neither worked.
推荐答案
下次使用原样的查询字符串.
Next time use the query string exactly as it is.
import requests
from bs4 import BeautifulSoup
search="2%2B2"
link="https://www.google.com/search?q="+search
headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}
source=requests.get(link,headers=headers).text
soup=BeautifulSoup(source,"html.parser")
answer=soup.find('span',id="cwos")
print(answer.text)
输出:
4
访问这些网址 - 它们不会返回相同的结果
Visit these urls - they do not return the same result
https://www.google.com/search?q=什么+是+2+2
https://www.google.com/search?q=2%2B2
https://www.google.com/search?q=2+2
这篇关于'NoneType' 对象在 BeautifulSoup 中没有属性 'text'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!