'NoneType'对象在BeautifulSoup中没有属性'text' [英] 'NoneType' object has no attribute 'text' in BeautifulSoup

查看:87
本文介绍了'NoneType'对象在BeautifulSoup中没有属性'text'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我搜索"什么是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆