【问题标题】:Configuring Google Custom Search to work like google.search()将 Google 自定义搜索配置为像 google.search() 一样工作
【发布时间】:2018-02-04 13:43:42
【问题描述】:

我有一个相对较大的项目,在谷歌搜索中,我们的缺失值返回了最佳结果。在 Python 中使用 google 搜索可以得到我需要的确切结果。当尝试使用自定义搜索来提升我的查询限制时,返回的结果与我需要的结果相差甚远。我有以下代码(建议在Searching in Google with Python 中),它返回的正是我所需要的,这与我在 Google 网站中搜索时完全相同,但由于 http 请求过多而被阻止...

from google import search

def google_scrape(url):
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    thepage = opener.open(url)
    soup = BeautifulSoup(thepage, "html.parser")
    return soup.title.text

i = 1
# queries = ['For. Policy Econ.','Int. J. Soc. For.','BMC Int Health Hum. Rights',
#            'Environ. Health Persp','Environ. Entomol.','Sociol. Rural.','Ecol. Soc.']

search_results = []    
abbrevs_searched = []   
url_results = []  

error_names = []
error = []

#Note, names_to_search is simply a longer version of the commented our queries list. 
for abbreviation in names_to_search:   
    query = abbreviation
    for url in search(query, num=2,stop=1):
        try:
            a = google_scrape(url)
            print(str(i) + ". " + a)
            search_results.append(a)
            abbrevs_searched.append(query)
            url_results.append(url)
            print(url)
            print(" ")
        except Exception as e:
            error_names.append(query)
            error.append(query)
            print("\n\n***************"," Exeption: ",e)
        i += 1

我通过以下方式设置了我的 Google 自定义搜索引擎代码...

import urllib
from bs4 import BeautifulSoup
import http.cookiejar
from apiclient.discovery import build
"""List of names to search on google"""
names_to_search = set(search_list_1+search_list)
service = build('customsearch', 'v1',developerKey="AIz**********************")
rse = service.cse().list(q="For. Policy Econ.",cx='*******************').execute()
rse

我的 Google 自定义搜索引擎设置设置为搜索 Google.com。到目前为止,除了站点是 Google.com 之外,所有其他设置都是默认设置。

【问题讨论】:

  • 您使用了哪个谷歌搜索 API?
  • 我在第一个示例中使用了来自 Google 的 Python 包的搜索,它可以按我的意愿工作,在第二个示例中我通过我的个人应用程序使用了自定义搜索引擎,它没有返回我想要的内容。我更新了导入以正确反映每个给定的代码块。
  • 你得到哪个错误?
  • 我没有收到错误。问题是我在自定义搜索引擎 API 上获得的结果与 google.search() python 模块大不相同,但是 Python 模块在一天内发送的 HTTP 请求数量有限,我不确定如何增加那个。我看到的每个尝试解决此问题的示例都使用自定义搜索引擎 API,但即使设置设置为 Google.com 的 google.search() 模块,我也无法获得结果。
  • 基本上,除了 HTTP 请求限制之外,Google.search() 可以完美地满足我的需求。 Google 自定义搜索能够通过 API 密钥连接到它,从而消除了 HTTP 请求限制,但返回的结果与 Google.search() 的结果相差甚远。我的目标是了解是否有办法使自定义搜索引擎的结果反映 Google.search() Python 模块的结果,或者是否可以将 API 密钥添加到我拥有的 Google.search() 模块错过了。

标签: python google-app-engine search


【解决方案1】:

据我所知,python 模块的问题不在于 python 模块的限制,而是 Google 不允许使用脚本抓取页面这一事实。当我运行您的程序(使用 google 模块)时,我收到了HTTP Error 503。这是因为在短时间内谷歌要求您进行验证码确认后,没有任何模块可以绕过验证码。这个问题的替代方法是使用网络搜索 API(例如,Google 自定义搜索 API),但几乎所有这些 API 都是付费选项(实际上它们通常提供查询限制较低的免费选项)。

网络搜索 API

谷歌自定义搜索 API

Google Custom Search API 的问题在于它旨在搜索您的网页。

Google 自定义搜索可让您为自己的网站、博客或网站集合创建搜索引擎。 Read more.

更新 - 2020 年 5 月

关于设置 Google 自定义搜索的下一部分已更新。

(我需要在 python 中进行谷歌搜索,而 selenium webdriver 不是一个选项。所以我决定使用谷歌自定义搜索 API 并回到我的 SO 答案,但它已经过时了(因为谷歌改变了它的开发人员界面)并且它不完整(只有描述如何创建谷歌自定义搜索引擎,但没有关于如何在 Python 中使用它的信息)。因此我更新了我的答案,但旧版本仍然是这个答案的一部分在下面。)

有一种方法可以通过以下步骤在 Python 中使用 Google 自定义搜索 API 搜索整个网络:

  1. 创建 Google 自定义搜索引擎
  2. 编辑 Google 自定义搜索引擎选项
  3. 创建自定义搜索 JSON API 密钥
  4. 通过 google-api-python-client 在 Python 中使用 Google 自定义搜索

创建 Google 自定义搜索引擎

要创建 Google 自定义搜索引擎,您需要转到 Google Custom Search homepage 并点击 添加 按钮:

您需要填写以下信息:

  • 要搜索的站点 - 您可以输入任何 URL,例如 www.anyurl.com
  • 搜索引擎的名称 - 您可以输入任何您想要的名称,例如 Google

填写完表格后,点击创建按钮:

编辑 Google 自定义搜索引擎选项

修改您的搜索引擎下点击按钮控制面板

要搜索的站点下(在设置的基本选项卡中)点击添加按钮:

输入http://www.example.org/,将其设置为仅包含我输入的这个特定页面或网址格式,然后点击保存

然后选择您的旧网站并点击删除按钮:

点击确定按钮确认删除:

搜索整个网络下切换ON-OFF按钮(使其保持开启状态):

创建自定义搜索 JSON API 密钥

自定义搜索 JSON API 右侧的 Programmatic Access 下单击按钮开始

你应该在这个page,在Before you start下,然后在Identify your application to Google with API key下,在自定义搜索引擎(免费版)用户点击按钮获取密钥

选择您要添加 Google 自定义搜索 API 的项目 (如果您还没有 Google Cloud 项目,您可以查看如何创建一个 here)然后点击按钮下一步

点击按钮完成

使用 google-api-python-client 在 Python 中使用 Google 自定义搜索

要在 Python 中使用 API,我们需要 搜索引擎 ID自定义搜索 JSON API 密钥

要查找搜索引擎 ID,请转到 Google Custom Search homepage 并点击搜索引擎名称 (Google):

复制搜索引擎 ID 并将其保存在某处(稍后我们将需要此 ID):

要查找自定义搜索 JSON API 密钥,请转到 Credentials tab of Google APIs dashboard,复制 API 密钥并将其保存在某处(我们也会使用此 API 密钥):

现在,我们需要安装 google-api-python-client,最简单的方法是使用 pip(更多信息请参见 google-api-python-client here):

pip install google-api-python-client

最后,您可以像这样在 Python 中使用 Google 自定义搜索(以下示例复制自 here):

import pprint
from googleapiclient.discovery import build

service = build('customsearch', 'v1', developerKey='your-API-key') # replace "'your-API-key' with your API key

# q is seacrh term that you want to search on google.com
res = service.cse().list(q='search term', cx='search-engine-ID').execute() # replace 'search-engine-ID' with your Search engine ID

pprint.pprint(res)

OLD(关于 Google 自定义搜索的部分答案)- 2017 年 8 月

这是前面关于如何使用 Google 自定义搜索搜索整个网络的说明。

答案的旧部分中的图像已被链接替换,因为它们占用了太多空间。还删除了创建 Google 自定义搜索引擎的步骤(从 Bangkokian 对此答案的答案复制为引用)并替换为 Bangkokian 答案的链接。(由于 Google 开发人员界面的变化,Bangkokian 答案中的这些步骤已过时。)

首先您需要创建一个 Google 自定义搜索引擎。

Bangkokian 在他的answer 中解释了如何创建 Google 自定义搜索引擎。

创建自定义搜索引擎后,您需要前往Google Custom Search并点击您已有的搜索引擎(可能是“Google”,在下图中用红色框标记):

Image - Google Custom Search

现在您需要在“搜索首选项”部分中,选择“搜索整个网络,但强调包含的网站”(第 7 步),然后单击“添加”按钮:

Image - GCS Preferences section

输入http://www.example.org/,将其设置为仅包含特定页面,然后点击保存:

Image - GCS Adding example.org website

然后选择您的旧网站并点击删除:

Image - GCS Deleting old website

更新它以保存更改:

Image - GCS Saving changes

关于 Google 自定义搜索的备注和注释的部分答案仍然有效。

很遗憾,Google 自定义搜索 API 不会提供与在网络上搜索相同的结果:

请注意,结果可能与您通过 Google 网页搜索获得的结果不匹配。 Read more.

但是,您可以将自定义搜索引擎配置为搜索整个网络。但是,在这种情况下,您的结果不太可能与 Google 网页搜索返回的结果相匹配。 Read more.

另外,你只能使用免费版:

本文仅适用于免费的基本自定义搜索引擎。您不能将 Google Site Search 设置为搜索整个网络。 Read more.

每天有 100 个搜索查询的限制:

对于 CSE 用户,API 每天免费提供 100 个搜索查询。 Read more.

FAROO API

只有另一种选择是使用来自其他搜索引擎的 API。而且似乎只有FAROO API是免费的。

编辑:

硒网络驱动程序

你可以在python中使用selenium webdriver来模拟浏览器的使用。有 options 可以使用 Firefox、Chrome、Edge 或 Safari 网络驱动程序(它实际上会打开 Chrome 并进行搜索),但这很烦人,因为您实际上并不想看到浏览器。但是有一个解决方案,你可以使用PhantomJS

PhantomJS 是一个可使用 JavaScript API 编写脚本的无头 WebKit。

here下载。提取出来看看下面的例子如何使用(我写了一个简单的类,你可以使用,你只需要改变PhantomJS的路径):

import time
from urllib.parse import quote_plus
from selenium import webdriver


class Browser:

    def __init__(self, path, initiate=True, implicit_wait_time = 10, explicit_wait_time = 2):
        self.path = path
        self.implicit_wait_time = implicit_wait_time    # http://www.aptuz.com/blog/selenium-implicit-vs-explicit-waits/
        self.explicit_wait_time = explicit_wait_time    # http://www.aptuz.com/blog/selenium-implicit-vs-explicit-waits/
        if initiate:
            self.start()
        return

    def start(self):
        self.driver = webdriver.PhantomJS(path)
        self.driver.implicitly_wait(self.implicit_wait_time)
        return

    def end(self):
        self.driver.quit()
        return

    def go_to_url(self, url, wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        self.driver.get(url)
        print('[*] Fetching results from: {}'.format(url))
        time.sleep(wait_time)
        return

    def get_search_url(self, query, page_num=0, per_page=10, lang='en'):
        query = quote_plus(query)
        url = 'https://www.google.hr/search?q={}&num={}&start={}&nl={}'.format(query, per_page, page_num*per_page, lang)
        return url

    def scrape(self):
        #xpath migth change in future
        links = self.driver.find_elements_by_xpath("//h3[@class='r']/a[@href]") # searches for all links insede h3 tags with class "r"
        results = []
        for link in links:
            d = {'url': link.get_attribute('href'),
                 'title': link.text}
            results.append(d)
        return results

    def search(self, query, page_num=0, per_page=10, lang='en', wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        url = self.get_search_url(query, page_num, per_page, lang)
        self.go_to_url(url, wait_time)
        results = self.scrape()
        return results




path = '<YOUR PATH TO PHANTOMJS>/phantomjs-2.1.1-windows/bin/phantomjs.exe' ## SET YOU PATH TO phantomjs
br = Browser(path)
results = br.search('For. Policy Econ.')
for r in results:
    print(r)

br.end()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    相关资源
    最近更新 更多