使用python请求库的google搜索

2024-04-24 03:20:31 发布

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

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

我刚开始尝试使用请求,但我仍然不太清楚如何从页面发送或请求其他内容。例如,我会

import requests

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

但我不知道现在该怎么做,例如,使用显示的搜索栏进行谷歌搜索。我读过《快速入门指南》,但对HTML帖子之类的东西不太熟悉,所以它并不是很有帮助。

有没有一个干净优雅的方法来做我所要求的?


Tags: 方法答案importcomhttp内容gethtml
3条回答

输入:

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
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}格式返回一个google结果数组。最重要的结果url是google('search query')[0]['url']

请求概述

Google搜索请求是一个标准的HTTP GET命令。它包含与查询相关的参数集合。这些参数以名称=值对的形式包含在请求URL中,并由与号(&;)字符分隔。参数包括诸如搜索查询之类的数据和唯一的CSE ID(cx),该ID标识发出HTTP请求的CSE。WebSearch或图像搜索服务返回XML结果以响应您的HTTP请求。

首先,必须在Control Panel of Custom Search Engine处获取CSE ID(cx参数)

然后,See the official Google Developers site for 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

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

相关问题 更多 >