用Python在谷歌上搜索

32

我想使用Python脚本在Google中搜索文本,并返回每个结果的名称、描述和URL。目前我正在使用以下代码:

from google import search

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

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

这将仅返回URL。如何返回每个URL的名称和描述?


1
你使用了哪个谷歌搜索API? - Jokab
提交程序化搜索查询违反了Google的网络管理员指南服务条款。在Google上运行此代码可能导致Google在您的IP地址上显示验证码。 - Stephen Ostermiller
7个回答

25
我假设你正在使用马里奥·维拉斯的这个库,因为他的代码中出现了stop=20参数。看起来这个库只能返回URL,使其极不完善。因此,你目前使用的库无法实现你想要的功能。
我建议你改用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)

4
我得到了一个错误信息:Traceback (most recent call last): File "Z:/test/test_google.py", line 57, in <module> from google import google ImportError: 无法导入名称google。 - Yarden
1
@Yarden 你首先必须下载该库。请使用链接中的说明。 - Jokab
这也适用于Python 3,供任何阅读评论的人使用。 - ands
1
它在Python3中对我不起作用,我不知道你在说什么。有一个问题正在处理中以支持Python3,但似乎还没有完成。 - wordsforthewise
1
似乎谷歌会因为这个解决方案而阻止你。 - yangliu2
显示剩余3条评论

15

虽然不完全符合我的要求,但我已经找到了一个不错的解决方案(如果我能将其改进,可能会对此进行编辑)。 我结合了像我之前一样在谷歌中搜索(只返回URL)和使用Beautiful Soup包解析HTML页面的方法:

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

这给我提供了页面标题和链接列表。

另外还有其他优秀的解决方案:

from googlesearch import search
import requests

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

5
导入错误:无法导入名称为'search'的模块。 - Pyd
1
@pyd 我来晚了 :D 试试 from googlesearch import search 用 'googlesearch' 代替 'google' ;) - Jayesh Dhandha
这个工作得很好,但是现在验证码阻止了未来的搜索。有什么解决办法吗? - Iker Olarra
这两个解决方案都不再适用了...... 你必须更新代码,以适应2022年,因为Google改变了许多东西。 - Just Me
如果你不想处理验证码或者应对谷歌不断变化的情况,Hartator的回答是一个不错的选择。https://stackoverflow.com/a/49989088/8803932 - undefined

9

我试过的大多数方法都无法正常工作,或者出现错误,例如尽管导入了包,也会出现搜索模块未找到的错误。或者我使用了selenium web driver,如果与FirefoxchromePhantom web browser一起使用,它可以很好地工作,但是在执行时间方面还是有点慢,因为它首先查询浏览器,然后返回搜索结果。

因此,我考虑使用Google API,它可以快速准确地返回结果

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

  1. 注册Google API以获取免费版的Google API密钥
  2. 现在搜索Google Custom Search并设置您的免费帐户以获取自定义搜索ID
  3. 现在在您的Python项目中添加此软件包(google-api-python-client) (可以通过编写!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"])

2
你能提供谷歌API Python客户端文档的链接吗? - Mitchell Posluns
这是一个不错的解决方案,但仅限于内部使用。对于企业级解决方案来说,它是昂贵的 :) - Jayesh Dhandha
2
我非常想使用你的解决方案。但是当设置自定义搜索ID时,它似乎只适用于特定的网站,例如“www.myownsite.com”。它并不适用于来自Google的所有结果。 - yangliu2

6
您还可以使用第三方服务,例如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

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

很遗憾,我想他们只有付费版本。即使是试用版也需要信用卡。 - Sameera K
你可以使用brightdata.com,它们目前似乎比SerpApi便宜,并且你可以免费测试。 - MartinG
SerpApi有一个免费计划,每月提供100次搜索,您无需输入信用卡信息即可注册。此外,还有一个新的Python库,可能更加简单易用:https://serpapi-python.readthedocs.io/en/latest/ - undefined

2

通常情况下,你不能通过在Python3中导入Google包来使用谷歌搜索功能。但是你可以在Python2中使用。

即使使用requests.get(url+query)方法,也无法进行爬取,因为Google会重定向到验证码页面以防止爬取。

可能的解决方法:

  • 你可以使用Python2编写代码。
  • 如果你想使用Python3编写代码,则可以创建2个文件,在Python2脚本中获取搜索结果。
  • 如果你感到困难,最好的方法是使用带有Python3运行时的Google Colab或Jupyter Notebook。这样你就不会收到任何错误提示。

1
你可以使用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())

0
作为替代方案,如果出于某种原因不必使用API,则可以使用BeautifulSoup网络爬虫库。
如果需要,您可以使用无限while循环从所有页面提取数据。 while循环将遍历所有页面,无论有多少个,直到满足某个条件为止。在我们的情况下,这是页面上按钮的存在(.d6cvqb a[id=pnnext] CSS选择器):
# stop the loop on the absence of the next page
if soup.select_one(".d6cvqb a[id=pnnext]"):
    params["start"] += 10
else:
    break

当您发出请求时,网站可能会认为您是一个机器人,为了防止这种情况发生,您需要发送包含请求中的user-agentheaders,然后该网站将假定您是一个用户并显示信息。

在线IDE中查看完整代码。

from bs4 import BeautifulSoup
import requests, json, lxml

# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
query = input("What would you like to search for? ")
params = {
    "q": query,          # query example
    "hl": "en",          # language
    "gl": "uk",          # country of the search, UK -> United Kingdom
    "start": 0,          # number page by default up to 0
    #"num": 100          # parameter defines the maximum number of results to return.
}

# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
}

page_limit = 10          # page limit if you don't need to fetch everything
page_num = 0

data = []

while True:
    page_num += 1
    print(f"page: {page_num}")
        
    html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
    soup = BeautifulSoup(html.text, 'lxml')
    
    for result in soup.select(".tF2Cxc"):
        title = result.select_one(".DKV0Md").text
        try:
           snippet = result.select_one(".lEBKkf span").text
        except:
           snippet = None
        links = result.select_one(".yuRUbf a")["href"]
      
        data.append({
          "title": title,
          "snippet": snippet,
          "links": links
        })
    
    # stop loop due to page limit condition
    if page_num == page_limit:
        break
    # stop the loop on the absence of the next page
    if soup.select_one(".d6cvqb a[id=pnnext]"):
        params["start"] += 10
    else:
        break
print(json.dumps(data, indent=2, ensure_ascii=False))

示例输出:

[
  {
    "title": "Web Scraping with Python - Pluralsight",
    "snippet": "There are times in which you need data but there is no API (application programming interface) to be found. Web scraping is the process of extracting data ...",
    "links": "https://www.pluralsight.com/paths/web-scraping-with-python"
  },
  {
    "title": "Chapter 8 Web Scraping | Machine learning in python",
    "snippet": "Web scraping means extacting data from the “web”. However, web is not just an anonymous internet “out there” but a conglomerat of servers and sites, ...",
    "links": "http://faculty.washington.edu/otoomet/machinelearning-py/web-scraping.html"
  },
  {
    "title": "Web scraping 101",
    "snippet": "This vignette introduces you to the basics of web scraping with rvest. You'll first learn the basics of HTML and how to use CSS selectors to refer to ...",
    "links": "https://cran.r-project.org/web/packages/rvest/vignettes/rvest.html"
  },
  other results ...
]

如果您想了解更多关于网站抓取的信息,可以查看13种从任何网站抓取公共数据的方法博客文章。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接