'NoneType'对象在BeautifulSoup中没有属性'text'

Muh*_*fil 5 python beautifulsoup web-scraping

当我搜索“ 什么是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)
Run Code Online (Sandbox Code Playgroud)

唯一的问题是idin soup.find,但是我非常仔细地选择了此id。我不要误会 我也尝试过answer=soup.find('span',class_="cwcot gsrt"),但是都没有用。

Dan*_* M. 5

解析网站时的一个大问题是,与浏览器中看到的相比,源代码可能看起来非常不同requests。不同之处在于 JavaScript,它可以在支持 JavaScript 的浏览器中极大地修改 DOM。

我建议3个选择:

  1. 使用requests来获取页面,然后仔细检查它 - 当页面由非 js 启用的代理检索时,该标记是否存在?
  2. 使用https://www.seleniumhq.org/作为您的代理 - 它本质上是一个功能齐全的浏览器,您可以通过编程方式控制它,包括 w/python。
  3. 使用 google 的搜索 API 而不是尝试抓取 html

  • “使用 Google 的搜索 API”:您指的是哪个 API?AFAIK,Google 已经 [8 年多了]没有公共搜索 API(/sf/ask/285807651/ -api 已被弃用)。 (3认同)

Bit*_*han 3

下次按原样使用查询字符串。

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)
Run Code Online (Sandbox Code Playgroud)

输出:

 4  
Run Code Online (Sandbox Code Playgroud)

访问这些网址 - 它们不会返回相同的结果

https://www.google.com/search?q=What+is+2+2

https://www.google.com/search?q=2%2B2

https://www.google.com/search?q=2+2