python - 无法抓取谷歌结果
问题描述
我是 python 新手,我正在学习automating boring stuff with python
,所以目前我在本书的网络抓取章节中。所以,我只想抓取搜索结果的标题。这是我的代码 -
import requests
from bs4 import BeautifulSoup
import webbrowser
term = 'python'
req = requests.get('https://www.google.com/search?q=' + term)
req.raise_for_status()
soup = BeautifulSoup(req.text, 'lxml')
title = soup.find('div', class_ = 'r')
print(title)
问题是这总是返回None
。我什至攻击了检查元素工具的屏幕截图,以便您可以看到我正在使用的名称div
。class
感谢任何帮助谢谢
解决方案
要从服务器获得正确的响应,请指定User-Agent
HTTP 标头:
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0'}
term = 'python'
req = requests.get('https://www.google.com/search?q=' + term, headers=headers)
req.raise_for_status()
soup = BeautifulSoup(req.content, 'lxml')
title = soup.find('div', class_ = 'r')
print(title.get_text(strip=True, separator=' '))
印刷:
Welcome to Python.org www.python.org www.python.org ...
推荐阅读
- python - 无法导入 stargazer(“ModuleNotFoundError: No module named 'stargazer')
- python - 选择查询后清除对 postgres 关系的访问共享锁定
- ffmpeg - gStreamer:使用 RAM 分区中的 jpeg 图像创建 RTSP 流
- sql - 如何替换以一组“特殊”字符(标签)开头和结尾的字符串
- rest - 是否可以使用亚马逊广告 API 获得帐户范围内的点击次数
- r - 正则表达式提取字符串匹配之间的数值
- excel - 请提供配方开发帮助?
- office-js - iOS Outlook 加载项不尊重对话框中外部站点的 Set-Cookies 标头
- javascript - 为什么附加到主进程上的“SIGINT”会触发子进程上的“退出”事件
- macos - Realm Studio:错误的进度信息(下载)