使用自定义搜索在Python中以编程方式搜索google

2024-05-22 01:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段使用pygoogle python模块的代码,它允许我以编程方式简洁地在google中搜索某个术语:

 g = pygoogle(search_term)
 g.pages = 1
 results = g.get_urls()[0:10]

我刚刚发现,不幸的是这已经停止了,取而代之的是谷歌自定义搜索。我看了其他相关的问题,但没有找到任何我可以使用的。我有两个问题:

1)google自定义搜索允许我做上面三行中我正在做的事情吗?

2)如果是-我在哪里可以找到示例代码来执行上面的操作?如果没有,那我用pygoogle做的事情还有什么选择呢?


Tags: 模块代码示例searchget编程google方式
1条回答
网友
1楼 · 发布于 2024-05-22 01:41:23

这是可能的。设置是。。。不是很简单,但最终的结果是,您可以用很少的代码从python搜索整个web。

总共有三个主要步骤。

第一步:获取Google API密钥

pygoogle的页面声明:

Unfortunately, Google no longer supports the SOAP API for search, nor do they provide new license keys. In a nutshell, PyGoogle is pretty much dead at this point.

You can use their AJAX API instead. Take a look here for sample code: http://dcortesi.com/2008/05/28/google-ajax-search-api-example-python-code/

。。。但实际上也不能使用AJAX API。你必须得到一个Google API密钥。https://developers.google.com/api-client-library/python/guide/aaa_apikeys对于简单的实验使用,我建议使用“服务器密钥”。

第二步:设置自定义搜索引擎以便可以搜索整个网站

实际上,旧的API是不可用的。现有的最好的新API是自定义搜索。它似乎只支持在特定的域中搜索,但是,在遵循this SO answer之后,您可以搜索整个web:

  1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
  2. Type a name and description for your search engine.
  3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
  4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
  5. Click any of the links under the Next steps section to navigate to your Control panel.
  6. In the left-hand menu, under Control Panel, click Basics.
  7. In the Search Preferences section, select Search the entire web but emphasize included sites.
  8. Click Save Changes.
  9. In the left-hand menu, under Control Panel, click Sites.
  10. Delete the site you entered during the initial setup process.

Google也推荐这种方法:https://support.google.com/customsearch/answer/2631040

第三步:为Python安装Google API客户端

pip install google-api-python-client,更多信息请点击此处:

第四步(奖励):搜索

因此,在设置此设置之后,您可以从几个地方执行代码示例:

结果是:

from googleapiclient.discovery import build
import pprint

my_api_key = "Google API key"
my_cse_id = "Custom Search Engine ID"

def google_search(search_term, api_key, cse_id, **kwargs):
    service = build("customsearch", "v1", developerKey=api_key)
    res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
    return res['items']

results = google_search(
    'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id, num=10)
for result in results:
    pprint.pprint(result)

经过一些调整后,您可以编写一些行为与代码片段完全相同的函数,但我将跳过这一步。

相关问题 更多 >