Skip to content

Instantly share code, notes, and snippets.

@bbelchak
Created October 14, 2010 17:12
Show Gist options
  • Save bbelchak/626584 to your computer and use it in GitHub Desktop.
Save bbelchak/626584 to your computer and use it in GitHub Desktop.
from urllib2 import *
from HTMLParser import HTMLParser
class Googleit(HTMLParser):
"""
Simple Python API to google. Returns a single numbered result from a search string.
Usage:
result = Googleit(term, number)
"""
def __init__(self, search, resnum):
HTMLParser.__init__(self)
self.search = search.replace('','+') # Thanks s3r1al :)
self.resnum = resnum
self.links = []
req = Request('http://www.google.co.uk/search?q=' + self.search)
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1')
r = urlopen(req)
html = r.read()
self.feed(html)
self.result = self.links[18:][self.resnum-1]
def handle_starttag(self, tag, attrs):
if tag == 'a' and attrs:
if attrs[0][0] == 'href':
if attrs[0][1][:4] == 'http':
self.links.append(attrs[0][1])
if __name__ == "__main__":
search_term = "let me google that for you"
resnum = 3
result = Googleit(search_term, resnum)
print result.result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment