brendano (owner)

Forks

Revisions

gist: 28405 Download_button fork
public
Description:
http://anyall.org/blog/2008/11/python-bindings-to-googles-ajax-search-api/
Public Clone URL: git://gist.github.com/28405.git
Embed All Files: show embed
ajaxgoogle.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""ajaxgoogle.py - Simple bindings to the AJAX Google Search API
(Just the JSON-over-HTTP bit of it, nothing to do with AJAX per se)
http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje
brendan o'connor - gist.github.com/28405 - anyall.org"""
try:
  import json
except ImportError:
  import simplejson as json
 
import urllib, urllib2
import os.path
 
TEMPLATE = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0"
 
if os.path.exists(os.environ['HOME'] + '/.ajaxgooglekey'):
  KEY = open(os.environ['HOME']+'/.ajaxgooglekey').read().strip()
else:
  KEY = None
if KEY:
  TEMPLATE += "&key=" + KEY
 
def search_url(q, **kwds):
  url = TEMPLATE
  url += "&q=" + urllib.quote(q)
  if kwds:
    url += "&" + urllib.urlencode(kwds)
  return url
 
def search(q, **kwds):
  """See options at http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje including:
rsz= large | small (8 vs 4)
start= <0-indexed offset>
hl= <language of searcher>
lr= <language of results>
safe= active | moderate | off
"""
  f = urllib2.urlopen(search_url(q, **kwds))
  ret = json.load(f)
  if ret['responseStatus']==200 and ret['responseData']: return ret['responseData']
  raise Exception("Google API error %s: %s\n (%s)" % (ret['responseStatus'],ret['responseDetails'],repr(ret)))
 
 
if __name__=='__main__':
  import sys
  from pprint import pprint
  if len(sys.argv) > 1:
    q = " ".join(sys.argv[1:])
  else: q = "query a question to whom in what sense"
  pprint(search(q))