使用Python的Google搜索网络抓取

pbe*_*ell 4 python google-search google-search-api python-2.7

最近我一直在学习很多python,以便在工作中的某些项目上工作。

目前,我需要对Google搜索结果进行一些网页抓取。我发现了几个站点,这些站点演示了如何使用ajax google api进行搜索,但是在尝试使用它之后,似乎不再受支持。有什么建议么?

我一直在寻找一种方法,但似乎无法找到当前有效的解决方案。

Dir*_*tra 10

你有两个选择。自己构建或使用 SERP API。

SERP API 将以格式化 JSON 响应的形式返回 Google 搜索结果。

我会推荐 SERP API,因为它更容易使用,而且您不必担心被 Google 屏蔽。

1. 搜索引擎结果页面API

我对scraperbox serp api有很好的经验。

您可以使用以下代码来调用API。确保替换YOUR_API_TOKEN为您的 scraperbox API 令牌。

import urllib.parse
import urllib.request
import ssl
import json
ssl._create_default_https_context = ssl._create_unverified_context

# Urlencode the query string
q = urllib.parse.quote_plus("Where can I get the best coffee")

# Create the query URL.
query = "https://api.scraperbox.com/google"
query += "?token=%s" % "YOUR_API_TOKEN"
query += "&q=%s" % q
query += "&proxy_location=gb"

# Call the API.
request = urllib.request.Request(query)

raw_response = urllib.request.urlopen(request).read()
raw_json = raw_response.decode("utf-8")
response = json.loads(raw_json)

# Print the first result title
print(response["organic_results"][0]["title"])
Run Code Online (Sandbox Code Playgroud)

2. 构建你自己的Python抓取工具

我最近写了一篇关于如何使用 Python 抓取搜索结果的深入博客文章。

这是一个快速总结。

首先,您应该获取 Google 搜索结果页面的 HTML 内容。

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

然后你可以使用BeautifulSoup来提取搜索结果。例如,以下代码将获取所有标题。

from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())
Run Code Online (Sandbox Code Playgroud)

您可以扩展此代码以提取搜索结果 URL 和描述。


Stu*_*tal 7

您随时可以直接抓取Google结果。为此,您可以使用https://google.com/search?q=<Query>将返回前10个搜索结果的URL 。

然后,您可以使用lxml为例分析页面。根据您的使用方式,您可以通过CSS选择器(.r a)或XPath选择器(//h3[@class="r"]/a)查询结果节点树。

在某些情况下,生成的URL将重定向到Google。通常,它包含一个查询参数q,该参数将包含实际的请求URL。

使用lxml和请求的示例代码:

from urllib.parse import urlencode, urlparse, parse_qs

from lxml.html import fromstring
from requests import get

raw = get("https://www.google.com/search?q=StackOverflow").text
page = fromstring(raw)

for result in page.cssselect(".r a"):
    url = result.get("href")
    if url.startswith("/url?"):
        url = parse_qs(urlparse(url).query)['q']
    print(url[0])
Run Code Online (Sandbox Code Playgroud)

关于google禁止您的IP的说明:根据我的经验,google仅在您开始向Google发送搜索请求垃圾邮件时禁止。如果Google认为您是机器人,则会以503响应。

  • 截至今天,这对我不起作用。当我查看 Google 搜索结果页面的源代码和 DOM 结构时,结果看起来好像是在 JavaScript 中加载和呈现的,这将防止这种幼稚的抓取。这对其他人有用吗? (2认同)
  • 不为我工作。`page.cssselect(".r a")` 是一个空数组。 (2认同)

Lei*_*oph 6

这是可用于刮除SERP的另一项服务(https://zenserp.com),它不需要客户端,而且价格便宜。

这是一个python代码示例:

import requests

headers = {
    'apikey': '',
}

params = (
    ('q', 'Pied Piper'),
    ('location', 'United States'),
    ('search_engine', 'google.com'),
    ('language', 'English'),
)

response = requests.get('https://app.zenserp.com/api/search', headers=headers, params=params)
Run Code Online (Sandbox Code Playgroud)