복붙노트

[PYTHON] Python 앱에서 Google 검색

PYTHON

Python 앱에서 Google 검색

파이썬 앱에서 Google 검색 쿼리를 실행하려고합니다. 내가 할 수있는 파이썬 인터페이스가 있습니까? 거기에 없다면 누가 어떤 Google API를 사용하여이 작업을 수행 할 수 있는지 알 수 있습니다. 감사.

해결법

  1. ==============================

    1.여기에 간단한 예제가 있습니다 (특이하게도 따옴표가 누락되었습니다 ;-). 웹에서 볼 수있는 대부분의 기능은 이전의 단종 된 SOAP API에 대한 Python 인터페이스입니다. 예를 들어 필자가 가리키는 바로는 더 새롭고 지원되는 AJAX API를 사용한다는 것입니다.

    여기에 간단한 예제가 있습니다 (특이하게도 따옴표가 누락되었습니다 ;-). 웹에서 볼 수있는 대부분의 기능은 이전의 단종 된 SOAP API에 대한 Python 인터페이스입니다. 예를 들어 필자가 가리키는 바로는 더 새롭고 지원되는 AJAX API를 사용한다는 것입니다.

    편집 : 여기 파이썬 2.6 예제가 더 필요합니다. & c; -) ... :

    #!/usr/bin/python
    import json
    import urllib
    
    def showsome(searchfor):
      query = urllib.urlencode({'q': searchfor})
      url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
      search_response = urllib.urlopen(url)
      search_results = search_response.read()
      results = json.loads(search_results)
      data = results['responseData']
      print 'Total results: %s' % data['cursor']['estimatedResultCount']
      hits = data['results']
      print 'Top %d hits:' % len(hits)
      for h in hits: print ' ', h['url']
      print 'For more results, see %s' % data['cursor']['moreResultsUrl']
    
    showsome('ermanno olmi')
    
  2. ==============================

    2.다음은 Python3에 포팅 된 Alex의 대답입니다.

    다음은 Python3에 포팅 된 Alex의 대답입니다.

    #!/usr/bin/python3
    import json
    import urllib.request, urllib.parse
    
    def showsome(searchfor):
      query = urllib.parse.urlencode({'q': searchfor})
      url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
      search_response = urllib.request.urlopen(url)
      search_results = search_response.read().decode("utf8")
      results = json.loads(search_results)
      data = results['responseData']
      print('Total results: %s' % data['cursor']['estimatedResultCount'])
      hits = data['results']
      print('Top %d hits:' % len(hits))
      for h in hits: print(' ', h['url'])
      print('For more results, see %s' % data['cursor']['moreResultsUrl'])
    
    showsome('ermanno olmi')
    
  3. ==============================

    3.이것에 대한 나의 접근 방식은 다음과 같습니다. http://breakingcode.wordpress.com/2010/06/29/google-search-python/

    이것에 대한 나의 접근 방식은 다음과 같습니다. http://breakingcode.wordpress.com/2010/06/29/google-search-python/

    몇 가지 코드 예 :

        # Get the first 20 hits for: "Breaking Code" WordPress blog
        from google import search
        for url in search('"Breaking Code" WordPress blog', stop=20):
            print(url)
    
        # Get the first 20 hits for "Mariposa botnet" in Google Spain
        from google import search
        for url in search('Mariposa botnet', tld='es', lang='es', stop=20):
            print(url)
    

    이 코드는 Google API를 사용하지 않으며 현재까지 작동하고 있습니다 (2012 년 1 월).

  4. ==============================

    4.나는 파이썬으로 새롭고 이것을 수행하는 방법을 조사하고 있었다. 제공된 예제 중 아무 것도 제대로 작동하지 않습니다. 많은 (몇 가지) 요청을하면 Google에서 차단하고 일부는 오래된 것입니다. 요청에서 헤더를 추가하는 Google 검색 html을 구문 분석하면 google이 html 구조를 다시 변경할 때까지 작동합니다. 동일한 로직을 사용하여 다른 검색 엔진에서 html (보기 소스)을 검색하여 검색 할 수 있습니다.

    나는 파이썬으로 새롭고 이것을 수행하는 방법을 조사하고 있었다. 제공된 예제 중 아무 것도 제대로 작동하지 않습니다. 많은 (몇 가지) 요청을하면 Google에서 차단하고 일부는 오래된 것입니다. 요청에서 헤더를 추가하는 Google 검색 html을 구문 분석하면 google이 html 구조를 다시 변경할 때까지 작동합니다. 동일한 로직을 사용하여 다른 검색 엔진에서 html (보기 소스)을 검색하여 검색 할 수 있습니다.

    import urllib2
    
    def getgoogleurl(search,siteurl=False):
        if siteurl==False:
            return 'http://www.google.com/search?q='+urllib2.quote(search)
        else:
            return 'http://www.google.com/search?q=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)
    
    def getgooglelinks(search,siteurl=False):
       #google returns 403 without user agent
       headers = {'User-agent':'Mozilla/11.0'}
       req = urllib2.Request(getgoogleurl(search,siteurl),None,headers)
       site = urllib2.urlopen(req)
       data = site.read()
       site.close()
    
       #no beatifulsoup because google html is generated with javascript
       start = data.find('<div id="res">')
       end = data.find('<div id="foot">')
       if data[start:end]=='':
          #error, no links to find
          return False
       else:
          links =[]
          data = data[start:end]
          start = 0
          end = 0        
          while start>-1 and end>-1:
              #get only results of the provided site
              if siteurl==False:
                start = data.find('<a href="/url?q=')
              else:
                start = data.find('<a href="/url?q='+str(siteurl))
              data = data[start+len('<a href="/url?q='):]
              end = data.find('&amp;sa=U&amp;ei=')
              if start>-1 and end>-1: 
                  link =  urllib2.unquote(data[0:end])
                  data = data[end:len(data)]
                  if link.find('http')==0:
                      links.append(link)
          return links
    

    용법:

    links = getgooglelinks('python','http://www.stackoverflow.com/')
    for link in links:
           print link
    

    (편집 1 : Google 검색을 특정 사이트로 좁히기위한 매개 변수 추가)

    (편집 2 :이 답변을 추가 할 때 자막 검색을위한 Python 스크립트를 코딩하고있었습니다. 최근 Github : Subseek에 업로드했습니다.)

  5. ==============================

    5.AJAX API가 작동하지 않으므로 Serp API와 같은 타사 서비스 (Google 검색 엔진 결과 래퍼)를 사용할 수 있습니다.

    AJAX API가 작동하지 않으므로 Serp API와 같은 타사 서비스 (Google 검색 엔진 결과 래퍼)를 사용할 수 있습니다.

    파이썬과의 통합은 쉽습니다.

    from lib.google_search_results import GoogleSearchResults
    
    params = {
        "q" : "Coffee",
        "location" : "Austin, Texas, United States",
        "hl" : "en",
        "gl" : "us",
        "google_domain" : "google.com",
        "api_key" : "demo",
    }
    
    query = GoogleSearchResults(params)
    dictionary_results = query.get_dictionary()
    

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

  6. from https://stackoverflow.com/questions/1657570/google-search-from-a-python-app by cc-by-sa and MIT license