2014-03-25 5 views
3

(I 찾고 시도했지만 다른 모든 답변은 urllib2를 사용하는 것 같다) 난 그냥 요청을 사용하려고 시작했습니다구글 검색

을,하지만 난 분명 아직도 아니에요 페이지에서 뭔가를 추가로 보내거나 요청하는 방법. 예를 들어, 나는

import requests 

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

을해야하지만 지금은, 예를 들어, 표시되는 검색 창을 사용하여 구글 검색을 수행하는 방법을 모르겠어요. 빠른 시작 가이드를 읽었지만 HTML POST와 그다지 익숙하지 않아서별로 도움이되지 못했습니다.

제가 묻는 것을 깨끗하고 세련되게 처리 할 수 ​​있습니까?

+0

입니다. 클라이언트 라이브러리없이 Google API를 사용할 수 있습니다. urllib.request 모듈을 사용하여 Python 3에서 Google 드라이브를 사용하고 있습니다. – Trimax

+0

글쎄, 나는 구글의 맥락에서만 그것을 의미하지는 않는다. 검색 할 수 있기를 원하는 다른 사이트/데이터베이스도있다. urllib/urllib2가 clunky/구식이 되었기 때문에 요즘은 요청 모듈이라고 생각했습니다. – James

+0

일부 메소드 (GET)는 매개 변수를 url로, 다른 메소드 (POST)를 데이터로 전달합니다. 두 사람 모두 헤더 (쌍 또는 키워드 및 값)를 허용 함 – Trimax

답변

6

요청 개요

Google 검색 요청은 표준 HTTP 명령을 GET입니다. 여기에는 검색어와 관련된 매개 변수 모음이 포함됩니다. 이러한 매개 변수는 요청 URL에 이름 = 값 쌍을 앰퍼샌드 (&) 문자, 즉으로 구분하여 포함됩니다. 매개 변수에는 검색 쿼리와 같은 데이터와 HTTP 요청을 작성하는 CSE를 식별하는 고유 한 CSE ID (cx)가 포함됩니다. WebSearch 또는 Image Search 서비스는 HTTP 요청에 대한 응답으로 XML 결과를 반환합니다.

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 

그리고 목록이 설명되어 있습니다

첫째, 당신은 See the official Google Developers site for Custom Search.

이 같은 많은 사례가있다, 그런 Control Panel of Custom Search Engine

에 당신의 CSE의 ID (CX 매개 변수)를 받아야합니다 사용할 수있는 매개 변수

4
import requests                                                  

def googlesearch(searchfor):                                              
    link = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % searchfor                                
    ua = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'}                 
    payload = {'q': searchfor}                                              
    response = requests.get(link, headers=ua, params=payload)                                      
    print response.text                                                

googlesearch('test') 

인쇄 :

{ "드 responseData"{ "결과"[{ "GsearchResultClass": "GwebSearch", "unescapedUrl": "http://www.speedtest.net/", "URL": "http://www.speedtest.net/" , "visibleUrl": "www.speedtest.net", "cacheUrl": "http://www.google.com/search?q \ u003dcache : M47_v0xF3m8J : www.speedtest.net", "title": "Ookla의 Speedtest.net - 글로벌 광대역 속도 \ u003cb \ u003e 테스트 \ u003c \ b \ u003e ","titleNoFormatting ":"Ookla의 Speedtest.net - 글로벌 광대역 속도 테스트 ","content ":"전세계의 인터넷 연결 대역폭을 \ u003cb \ u003e/test \ u003c/b \ u003e 이 \ n 대화 형 광대역 속도 \ u003cb \ u003estest \ u Ookla로부터 003c/B의 \의 u003E 페이지 "}

+4

"Google 웹 검색 API를 더 이상 사용할 수 없으므로 Google 맞춤 검색 API로 마이그레이션하십시오." – mootmoot

+1

이것은 작동하지 않습니다 :'{ "responseData": null, "responseDetails": "Google 웹 검색 API를 더 이상 사용할 수 없습니다. Google 맞춤 검색 API (https://developers.google.com/custom)로 마이그레이션하십시오. -search /) ","responseStatus ": 403}' – tumbleweed

0

입력 :.

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
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']

관련 문제