#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Foretag en billedsøgning på Google.

import lxml.html
from lxml import etree
import urllib
import urllib2
import sys
import urlparse

query = " ".join(sys.argv[1:])

# Create search URL
# For some reason we have to tell the resolution of our monitor to get
# any results. We specify 100x100 pixels
search_url = ("http://www.google.com/search?hl=da&tbm=isch&q="+urllib.quote(query)
     +"&as_qdr=all&biw=100&bih=100&safe=off")

# Query google
try:
    request = urllib2.Request(search_url)
    request.add_header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT "
                       "6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8")
    request.add_header("Referer", "http://www.google.com")
    result = urllib2.urlopen(request)
except Exception:
    print "Problem ved forespørgsel til Google"
    sys.exit(-1)

# Parse HTML
try:
    parser = etree.HTMLParser()
    tree = lxml.etree.parse(result, parser)
except:
    print "Fejl under parsing af Googles HTML-kode"
    sys.exit(-1)

# Extract results
result_fields = tree.xpath('//li[@class="rg_li"]')

if len(result_fields) > 0:
    field = result_fields[0]
    try:
        url = field.xpath('a[@class="rg_l"]')[0].get('href')
        print urlparse.parse_qs(urlparse.urlparse(url).query)["imgurl"][0]
    except Exception:
        print "Problem ved udtrækning af billed-URL fra HTML parsetræ"
else:
    print "Ingen resultater"
