bing_images.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. ## Bing (Images)
  2. #
  3. # @website https://www.bing.com/images
  4. # @provide-api yes (http://datamarket.azure.com/dataset/bing/search), max. 5000 query/month
  5. #
  6. # @using-api no (because of query limit)
  7. # @results HTML (using search portal)
  8. # @stable no (HTML can change)
  9. # @parse url, title, img_src
  10. #
  11. # @todo currently there are up to 35 images receive per page, because bing does not parse count=10. limited response to 10 images
  12. from urllib import urlencode
  13. from cgi import escape
  14. from lxml import html
  15. from yaml import load
  16. import re
  17. # engine dependent config
  18. categories = ['images']
  19. paging = True
  20. # search-url
  21. base_url = 'https://www.bing.com/'
  22. search_string = 'images/search?{query}&count=10&first={offset}'
  23. # do search-request
  24. def request(query, params):
  25. offset = (params['pageno'] - 1) * 10 + 1
  26. # required for cookie
  27. language = 'en-US'
  28. search_path = search_string.format(
  29. query=urlencode({'q': query}),
  30. offset=offset)
  31. params['cookies']['SRCHHPGUSR'] = \
  32. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0]
  33. params['url'] = base_url + search_path
  34. return params
  35. # get response from search-request
  36. def response(resp):
  37. results = []
  38. dom = html.fromstring(resp.content)
  39. # init regex for yaml-parsing
  40. p = re.compile( '({|,)([a-z]+):(")')
  41. # parse results
  42. for result in dom.xpath('//div[@class="dg_u"]'):
  43. link = result.xpath('./a')[0]
  44. # parse yaml-data (it is required to add a space, to make it parsable)
  45. yaml_data = load(p.sub( r'\1\2: \3', link.attrib.get('m')))
  46. title = link.attrib.get('t1')
  47. #url = 'http://' + link.attrib.get('t3')
  48. url = yaml_data.get('surl')
  49. img_src = yaml_data.get('imgurl')
  50. # append result
  51. results.append({'template': 'images.html',
  52. 'url': url,
  53. 'title': title,
  54. 'content': '',
  55. 'img_src': img_src})
  56. # TODO stop parsing if 10 images are found
  57. if len(results) >= 10:
  58. break
  59. # return results
  60. return results