在 Google 中搜索 Python

Searching in Google with Python

我想使用 python 脚本和 return 每个结果的名称、描述和 URL 在 Google 中搜索文本。我目前正在使用此代码:

from google import search

ip=raw_input("What would you like to search for? ")

for url in search(ip, stop=20):
     print(url)

这 return 只有 URL 的。我如何 return 每个 URL 的名称和描述?

我假设您正在使用 this library by Mario Vilas 因为 stop=20 参数出现在他的代码中。似乎这个库除了 URL 之外无法 return 任何东西,这使得它非常未开发。因此,您当前使用的库无法实现您想做的事情。

我建议您改为使用 abenassi/Google-Search-API。然后你可以简单地做:

from google import google
num_page = 3
search_results = google.search("This is my query", num_page)
for result in search_results:
    print(result.description)

不完全是我想要的,但我现在发现自己是一个不错的解决方案(如果我能做得更好,我可能会编辑它)。我像以前一样在 Google 中搜索(仅返回 URL)和用于解析 HTML 页面的 Beautiful Soup 包:

from googlesearch import search
import urllib
from bs4 import BeautifulSoup

def google_scrape(url):
    thepage = urllib.urlopen(url)
    soup = BeautifulSoup(thepage, "html.parser")
    return soup.title.text

i = 1
query = 'search this'
for url in search(query, stop=10):
    a = google_scrape(url)
    print str(i) + ". " + a
    print url
    print " "
    i += 1

这给了我一个页面标题列表和 link。

还有另一个很棒的解决方案:

from googlesearch import search
import requests

for url in search(ip, stop=10):
            r = requests.get(url)
            title = everything_between(r.text, '<title>', '</title>')

我尝试使用其中的大多数,但对我来说没有用,或者给出了错误,例如尽管导入了包却找不到搜索模块。或者我确实使用了 selenium 网络驱动程序,如果与 FirefoxchromePhantom web browser, 但仍然感觉执行时间有点慢,先查询浏览器再返回搜索结果。

所以我想到了使用 google api,它的工作速度非常快,returns 结果准确.

在我在这里分享代码之前,有几个要遵循的快速提示:-

  1. 在 Google Api 上注册以获得 Google Api 密钥(免费版)
  2. 现在搜索 Google 自定义搜索并设置您的免费帐户以获取自定义搜索 ID
  3. 现在将这个包(google-api-python-client)添加到您的 python 项目中 (可以通过写 !pip install google-api-python-client )

就是这样,您现在要做的就是 运行 此代码:-

from googleapiclient.discovery import build

my_api_key = "your API KEY TYPE HERE"
my_cse_id = "YOUR CUSTOM SEARCH ENGINE ID TYPE HERE"

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("YOUR SEARCH QUERY HERE",my_api_key,my_cse_id,num=10) 

for result in results:
      print(result["link"])

您还可以使用第三方服务,例如 SerpApi,它是 Google 搜索引擎结果。它解决了必须租用代理和解析 HTML 结果的问题。 JSON产量特别丰富

很容易与Python集成:

from serpapi import GoogleSearch

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

query = GoogleSearch(params)
dictionary_results = query.get_dict()

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

通常,您不能通过在 python3 中导入 google 包来使用 python 中的 google 搜索功能。但你可以在 python2.

中使用它

即使使用 requests.get(url+query) scraping 也不会执行,因为 google 通过重定向来防止抓取到验证码页面。

可能的方式:

  • 你可以在python2
  • 中编写代码
  • 如果你想把它写在python3中,那么制作2个文件并从python2脚本中检索搜索结果。
  • 如果发现困难,最好的方法是使用 Google Colab 或 Jupyter Notebook 和 python3 运行时。你不会得到任何错误。

您可以使用 Google Search Origin 包,它集成了 google 上可用的大部分参数(它包括 dorks 和过滤器)。它基于 google 官方文档。此外,使用它会创建一个对象,因此它很容易修改。有关详细信息,请查看此处的项目:https://pypi.org/project/google-search-origin/

这里是一个如何使用它的例子:

import google_search_origin


if __name__ == '__main__':
    # Initialisation of the class
    google_search = google_search_origin.GoogleSearchOrigin(search='sun')
    
    # Request from the url assembled
    google_search.request_url()

    # Display the link parsed depending on the result
    print(google_search.get_all_links())

    # Modify the parameter
    google_search.parameter_search('dog')

    # Assemble the url
    google_search.assemble_url()

    # Request from the url assembled
    google_search.request_url()

    # Display the raw text depending on the result
    print(google_search.get_response_text())