bing_images.py 2.3 KB

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