50

PythonアプリからGoogle検索クエリを実行しようとしています。これを可能にするPythonインターフェースはありますか?誰もいない場合は、どのGoogleAPIでこれを実行できるかわかりません。ありがとう。

4

4 に答える 4

72

ここに簡単な例があります(特に引用符が欠落しています;-)。Webに表示されるもののほとんどは、廃止された古いSOAP APIへのPythonインターフェースです。私が指摘している例では、新しくサポートされているAJAX APIを使用しています。これは、間違いなく必要なものです!-)

編集:これは、必要なすべての引用符を含む、より完全なPython 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')
于 2009-11-01T16:30:16.670 に答える
17

Python3に移植されたアレックスの答えは次のとおりです

#!/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')
于 2009-11-01T19:09:14.913 に答える
11

これに対する私のアプローチは次のとおりです: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)

このコードはGoogleAPIを使用しておらず、現在も機能していることに注意してください(2012年1月)。

于 2012-01-10T10:57:45.337 に答える
6

私はpythonが初めてで、これを行う方法を調査していました。提供された例はどれも私にとって適切に機能していません。多くの(少ない)リクエストを行うと、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

于 2013-02-07T05:23:07.040 に答える