使用Python的requests库进行Google搜索

15

(我曾试图查询其他答案,但所有其他答案似乎都在使用urllib2)

我刚开始尝试使用requests,但我仍然不太清楚如何从页面发送或请求额外的内容。例如,我将有

import requests

r = requests.get('http://google.com')

但是我现在不知道怎么做,例如,如何使用呈现的搜索栏进行谷歌搜索。我已经阅读了快速入门指南,但我对HTML POST等内容不太熟悉,所以它并没有提供太多帮助。

有没有一种简洁优雅的方法来完成我所要求的操作?


您可以在没有客户端库的情况下使用Google API。我正在使用Python 3中的urllib.request模块来使用Google Drive。 - Trimax
我并不是只在谷歌的情况下使用,还有其他网站/数据库也想要搜索。另外,我认为现在的标准是使用requests模块,因为urllib/urllib2已经变得笨重/过时了。 - James
一些方法(GET)通过URL传递它们的参数,而其他方法(POST)则通过数据传递。两者都允许使用标题(键值对或关键字和值)。 - Trimax
6个回答

17

请求概述

Google搜索请求是一个标准的HTTP GET命令。它包括一组与您的查询相关的参数。这些参数作为名称=值对包含在请求URL中,由和号(&)字符分隔。这些参数包括搜索查询数据和唯一的CSE ID(cx),该ID标识了发出HTTP请求的CSE。WebSearch或Image Search服务将在响应您的HTTP请求时返回XML结果。

首先,您必须在自定义搜索引擎控制面板获取您的CSE ID(cx参数)。

然后,请参阅官方Google开发者网站Custom Search页面

有许多类似于此的示例:

http://www.google.com/search?
  start=0
  &num=10
  &q=red+sox
  &cr=countryCA
  &lr=lang_fr
  &client=google-csbe
  &output=xml_no_dtd
  &cx=00255077836266642015:u-scht7a-8i

这里解释了你可以使用的参数列表。


14
import requests 
from bs4 import BeautifulSoup

headers_Get = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.5',
        'Accept-Encoding': 'gzip, deflate',
        'DNT': '1',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
    }


def google(q):
    s = requests.Session()
    q = '+'.join(q.split())
    url = 'https://www.google.com/search?q=' + q + '&ie=utf-8&oe=utf-8'
    r = s.get(url, headers=headers_Get)

    soup = BeautifulSoup(r.text, "html.parser")
    output = []
    for searchWrapper in soup.find_all('h3', {'class':'r'}): #this line may change in future based on google's web page structure
        url = searchWrapper.find('a')["href"] 
        text = searchWrapper.find('a').text.strip()
        result = {'text': text, 'url': url}
        output.append(result)

    return output

将以 {'text': text, 'url': url} 格式返回一个搜索结果数组。其中第一个结果的 URL 是 google('search query')[0]['url']


6
FYI,自动化脚本搜索违反了Google的服务条款,你应该使用Google的自定义搜索API代替(https://developers.google.com/custom-search/docs/tutorial/creatingcse)。这样更简洁,并且无需使用BeautifulSoup。 - Yu Chen

5

输入:

import requests

def googleSearch(query):
    with requests.session() as c:
        url = 'https://www.google.co.in'
        query = {'q': query}
        urllink = requests.get(url, params=query)
        print urllink.url

googleSearch('Linkin Park')

输出:

https://www.google.co.in/?q=Linkin+Park


1

发送一个带有多个查询参数的请求的可读方式是将URL参数 作为字典 传递:

params = {
  'q': 'minecraft', # search query
  'gl': 'us',       # country where to search from   
  'hl': 'en',       # language 
}

requests.get('URL', params=params)

然而,为了获取在浏览器中看到的实际响应(输出/文本/数据),你需要发送额外的headers,更具体地说是user-agent,这是必要的,以便在机器人或浏览器发送伪造的user-agent字符串来表示自己是不同的客户端时,充当“真实”的用户访问。

你的请求可能被阻止的原因是默认的 requests 用户代理是 python-requests,网站识别到了它。检查你的用户代理是什么

您可以在我写的关于如何减少网络爬虫被封锁的机会的博客文章中了解更多信息。

通过user-agent

headers = {
    'User-agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}

requests.get('URL', headers=headers)

在线IDE中的代码和示例:

from bs4 import BeautifulSoup
import requests, lxml

headers = {
    'User-agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}

params = {
  'q': 'minecraft',
  'gl': 'us',
  'hl': 'en',
}

html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

for result in soup.select('.tF2Cxc'):
  title = result.select_one('.DKV0Md').text
  link = result.select_one('.yuRUbf a')['href']
  print(title, link, sep='\n')

另外,您还可以使用SerpApi的Google Organic API来实现同样的功能。这是一个付费API,但有免费计划。

不同之处在于您无需从头开始创建和维护它。

集成的代码:

import os
from serpapi import GoogleSearch

params = {
  "engine": "google",
  "q": "tesla",
  "hl": "en",
  "gl": "us",
  "api_key": os.getenv("API_KEY"),
}

search = GoogleSearch(params)
results = search.get_dict()

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

免责声明,我在SerpApi工作。

0
在这段代码中,通过使用bs4,您可以获取所有的h3print它们的文本。
# Import the beautifulsoup 
# and request libraries of python.
import requests
import bs4
  
# Make two strings with default google search URL
# 'https://google.com/search?q=' and
# our customized search keyword.
# Concatenate them
text= "c++ linear search program"
url = 'https://google.com/search?q=' + text
  
# Fetch the URL data using requests.get(url),
# store it in a variable, request_result.
request_result=requests.get( url )
  
# Creating soup from the fetched request
soup = bs4.BeautifulSoup(request_result.text,"html.parser")
filter=soup.find_all("h3")
for i in range(0,len(filter)):
    print(filter[i].get_text())

0

你可以使用“webbrowser”,我认为没有比这更简单的了:

import webbrowser

query = input('Enter your query: ')
webbrowser.open(f'https://google.com/search?q={query}')

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