如何用 Python 快速抓取 Google 搜索?
![](https://img.haomeiwen.com/i10458593/c59ada52bae44b68.png)
![](https://img.haomeiwen.com/i10458593/7a29e929f93e6a12.gif)
![](https://img.haomeiwen.com/i10458593/e1f220956cd13158.png)
文章发布于公号【数智物语】 (ID:decision_engine),关注公号不错过每一篇干货。
来源 | CSDN(ID:CSDNnews)
作者 | linksc
译者 |弯月,责编 | 郭芮
本文是通过 requests 和 Beautiful Soup 抓取 Google 搜索的快速指南。
以下为译文:
自从2011年 Google Web Search API 被弃用以来,我一直在寻找其他的方法来抓取Google。我需要一种方法,让我的 Python 脚本从 Google 搜索中获取链接。于是,我自己想出了一种方法,而本文正是通过 requests 和 Beautiful Soup 抓取 Google 搜索的快速指南。
首先,让我们来安装一些依赖项。请将以下内容保存成文本文件 requirements.txt:
requests
bs4
接下来,运行 pip install -r requirements.txt 命令来安装依赖项。然后将其导入到你的脚本中。
importurllib
importrequests
frombs4importBeautifulSoup
为了执行搜索,你需要在URL中为 Google 提供查询参数。此外,所有空格都必须用+代替。为了构建URL,我们需要设置正确的查询格式,并其放入q参数中。
query="hackernoon How To Scrape Google With Python"
query= query.replace(' ','+')
URL= f"https://google.com/search?q={query}"
Google 会针对移动设备和台式机返回不同的搜索结果。因此,我们需要指定适当的用户代理。
# desktop user-agent
USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0"
# mobile user-agent
MOBILE_USER_AGENT="Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36"
发送请求很简单。但是,requests需要将 user-agent 放在请求的头部。为了设置正确的头部,我们必须传给headers一个字典。
headers= {"user-agent": MOBILE_USER_AGENT}
resp= requests.get(URL, headers=headers)
接下来,我们需要检查请求是否成功。最简单的方法是检查状态码。如果返回200,则表示成功。然后,我们需要将其放入 Beautiful Soup 中以解析内容。
ifresp.status_code == 200:
soup = BeautifulSoup(resp.content,"html.parser")
接下来是解析数据,并从页面提取所有的链接。我们可以利用 Beautiful Soup 简单地完成这项工作。在便利每个链接时,我们需要将结果存储到一个列表中。
results = []
forg in soup.find_all('div', class_='r'):
anchors = g.find_all('a')
ifanchors:
link= anchors[0]['href']
title = g.find('h3').text
item = {
"title": title,
"link":link
}
results.append(item)
print(results)
这样就可以了。这个脚本非常简单,而且容易出错。但至少它能带你入门,从此你就可以编写自己的 Google 爬虫了。你可以从 GitHub上下载整个脚本,地址是:https://github.com/getlinksc/scrape_google。
原文:https://hackernoon.com/how-to-scrape-google-with-python-bo7d2tal
本文为 CSDN 翻译,转载请注明来源出处。
![](https://img.haomeiwen.com/i10458593/35946933f8ac893d.png)
风鸟企业负面信息免费查询平台:http://www.yansu.net.cn/
![](https://img.haomeiwen.com/i10458593/862417b6fdff6659.png)
星标我,每天多一点智慧
![](https://img.haomeiwen.com/i10458593/ee78a92f4622dd99.png)