![](/img/trans.png)
[英]BeautifulSoup: AttributeError: 'NoneType' object has no attribute 'text'
[英]'NoneType' object has no attribute 'text' in BeautifulSoup
当我搜索“ What is 2+2 ”时,我试图抓取 Google 结果,但以下代码返回'NoneType' object has no attribute 'text'
。 请帮助我实现所需的目标。
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
,但是我非常soup.find
选择了这个id。 我不应该弄错。 我也试过answer=soup.find('span',class_="cwcot gsrt")
,但都没有奏效。
解析网站时的一个大问题是,与requests
看到的相比,源代码在浏览器中的外观可能大不相同。 不同之处在于 javascript,它可以在支持 javascript 的浏览器中极大地修改 DOM。
我建议3个选项:
requests
来获取页面,然后仔细检查它 - 当页面被非 js 启用的代理检索时,该标签是否存在?下次使用原样的查询字符串。
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
访问这些网址 - 它们不会返回相同的结果
https://www.google.com/search?q=What+is+2+2
运行代码时,您可能会遇到 AttributeError:
shell: AttributeError: 'NoneType' 对象没有属性 'text'
如果是这种情况,请退后一步并检查您以前的结果。 是否有任何值为 None 的项目? 您可能已经注意到页面的结构并不完全统一。 那里可能有一个广告,其显示方式与正常职位发布的方式不同,这可能会返回不同的结果
参考: https://realpython.com/beautiful-soup-web-scraper-python/#extract-text-from-html-elements 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.