来自Python应用程序的Google搜索

Res*_*Res 51 python api google-search-api

我正在尝试从python应用程序运行谷歌搜索查询.有没有任何python接口可以让我这样做?如果没有人知道哪个Google API可以让我这样做.谢谢.

Ale*_*lli 71

有一个简单的例子这里(缺少独有的一些报价;-).你在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')
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,2010年11月已弃用其依赖的[Google Web搜索API](http://code.google.com/apis/websearch/).自定义搜索API应该替换它,但需要您配置要搜索的网址列表 - 而不是整个网络. (11认同)
  • 在我的本地Linux机器上试过这个,然后谷歌认为我是一个机器人,我的浏览器中的任何搜索都是验证码!我不应该在工作中尝试这个,只是为使用此功能的人提醒.添加用户代理和引荐来使其看起来更像是真实的请求! (3认同)
  • 截至今天(2014.06.10),这在我的IPython/Python2.7.6上有效 (3认同)

Joh*_*ooy 17

这是Alex的回答移植到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')
Run Code Online (Sandbox Code Playgroud)


小智 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)
Run Code Online (Sandbox Code Playgroud)

请注意,此代码不使用Google API,并且至今仍在使用(2012年1月).


Fed*_*tta 6

我是python的新手,我正在调查如何做到这一点.所提供的示例都不适合我.如果你提出很多(很少)请求,有些会被谷歌阻止,有些已经过时了.解析谷歌搜索html(在请求中添加标题)将一直有效,直到谷歌再次更改html结构.你可以使用相同的逻辑在任何其他搜索引擎中搜索,查看html(view-source).

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
Run Code Online (Sandbox Code Playgroud)

用法:

links = getgooglelinks('python','http://www.stackoverflow.com/')
for link in links:
       print link
Run Code Online (Sandbox Code Playgroud)

(编辑1:添加参数以将谷歌搜索范围缩小到特定网站)

(编辑2:当我添加这个答案时,我正在编写一个Python脚本来搜索字幕.我最近将它上传到Github:Subseek)