【问题标题】:Google Search Web Scraping with Python使用 Python 进行 Google 搜索网页抓取
【发布时间】:2016-12-01 20:22:26
【问题描述】:

我最近学习了很多 python 来处理一些工作中的项目。

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

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

【问题讨论】:

  • 可以在没有 API 的情况下使用 Google 进行搜索,但如果他们怀疑您是机器人,您很可能会被 Google 禁止。阅读 TOS,您可能需要付费才能以任何重要的方式使用他们的 API。
  • 我研究了如何在没有 API 的情况下做到这一点,我必须更改我的标头/用户代理信息。但即使我这样做了,我仍然无法得到结果。如果这样可行,我会在每个请求之间放置一个睡眠计时器,以免被视为机器人。
  • 我写了一个谷歌搜索机器人,效果很好,但是由于使用机器人直接违反了谷歌的服务条款,我不打算发布它。无论您想做什么,都可以通过官方 API。

标签: python python-2.7 google-search google-search-api


【解决方案1】:

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

然后您可以使用lxml 来解析页面。根据您使用的内容,您可以通过 CSS-Selector (.r a) 或使用 XPath-Selector (//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])

关于谷歌禁止你的 IP 的说明:根据我的经验,谷歌只禁止 如果你开始用搜索请求向谷歌发送垃圾邮件。它会回应 如果 Google 认为您是机器人,则返回 503。

【讨论】:

  • 谢谢,我能够得到与此类似的工作。
  • 截至今天,这对我不起作用。当我查看 Google 搜索结果页面的源代码和 DOM 结构时,看起来好像结果是在 JavaScript 中加载和呈现的,这可以防止这种幼稚的抓取。这对其他人有用吗?
  • @Lane Rettig 工作正常。
  • 不适合我。 page.cssselect(".r a") 是一个空数组。
【解决方案2】:

这是另一种可用于抓取 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)

【讨论】:

  • 我使用 API 已经 2 个月了,因为它是唯一一个提供免费计划的开始。运行良好,到目前为止没有遇到任何问题!
【解决方案3】:

您有 2 个选项。自行构建或使用 SERP API。

SERP API 会将 Google 搜索结果作为格式化的 JSON 响应返回。

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

1. SERP API

我对@9​​87654321@ 有很好的体验。

您可以使用以下代码调用 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"])

2。构建自己的 Python 爬虫

我最近在how to scrape search results with 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")

然后您可以使用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())

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

【讨论】:

  • #1 不适用于他们自己页面上的基本示例。猜猜谷歌也找到了他们。
【解决方案4】:

您还可以使用第三方服务,例如 Serp API - 我编写并运行了这个工具 - 这是一个付费的 Google 搜索引擎结果 API。它解决了被阻塞的问题,你不必租用代理并自己做结果解析。

很容易与 Python 集成:

from lib.google_search_results import GoogleSearchResults

params = {
    "q" : "Coffee",
    "location" : "Austin, Texas, United States",
    "hl" : "en",
    "gl" : "us",
    "google_domain" : "google.com",
    "api_key" : "demo",
}

query = GoogleSearchResults(params)
dictionary_results = query.get_dictionary()

GitHub:https://github.com/serpapi/google-search-results-python

【讨论】:

  • 您需要为此 API 密钥付费。
  • @TejasKrishnaReddy 有一个非商业免费计划,每月搜索 100 次。
猜你喜欢
  • 2021-06-12
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 2020-10-04
  • 2021-05-08
相关资源
最近更新 更多