[enh] google images refactor

This commit is contained in:
asciimoo 2013-10-19 23:12:18 +02:00
parent 225c7ecbcf
commit 83af0b6224

View file

@ -1,28 +1,26 @@
#!/usr/bin/env python #!/usr/bin/env python
from urllib import quote from urllib import urlencode
from lxml import html from json import loads
from urlparse import urljoin
categories = ['images'] categories = ['images']
base_url = 'https://www.google.com/' search_url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&start=0&rsz=large&safe=off&filter=off&'
search_url = base_url+'search?tbm=isch&hl=en&q='
def request(query, params): def request(query, params):
global search_url global search_url
query = quote(query.replace(' ', '+'), safe='+') params['url'] = search_url + urlencode({'q': query})
params['url'] = search_url + query
return params return params
def response(resp): def response(resp):
global base_url global base_url
results = [] results = []
dom = html.fromstring(resp.text) search_res = loads(resp.text)
for result in dom.xpath('//table[@class="images_table"]//a'): if 'responseData' not in search_res:
url = urljoin(base_url, result.attrib.get('href')) return []
img = result.xpath('.//img')[0] for result in search_res['responseData']['results']:
title = ' '.join(result.xpath('..//text()')) url = result['originalContextUrl']
content = '<img src="%s" alt="%s" />' % (img.attrib.get('src', ''), title) title = result['title']
content = result['content']+'<br /><a href="%s"><img src="%s" title="%s" style="max-width: 500px; "/></a>' % (result['url'], result['url'], title)
results.append({'url': url, 'title': title, 'content': content}) results.append({'url': url, 'title': title, 'content': content})
return results return results