bing_images.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. safesearch = True
  23. # search-url
  24. base_url = 'https://www.bing.com/'
  25. search_string = 'images/search?{query}&count=10&first={offset}'
  26. thumb_url = "http://ts1.mm.bing.net/th?id={ihk}"
  27. # safesearch definitions
  28. safesearch_types = {2: 'STRICT',
  29. 1: 'DEMOTE',
  30. 0: 'OFF'}
  31. # do search-request
  32. def request(query, params):
  33. offset = (params['pageno'] - 1) * 10 + 1
  34. # required for cookie
  35. if params['language'] == 'all':
  36. language = 'en-US'
  37. else:
  38. language = params['language'].replace('_', '-')
  39. search_path = search_string.format(
  40. query=urlencode({'q': query}),
  41. offset=offset)
  42. params['cookies']['SRCHHPGUSR'] = \
  43. 'NEWWND=0&NRSLT=-1&SRCHLANG=' + language.split('-')[0] +\
  44. '&ADLT=' + safesearch_types.get(params['safesearch'], 'DEMOTE')
  45. params['url'] = base_url + search_path
  46. return params
  47. # get response from search-request
  48. def response(resp):
  49. results = []
  50. dom = html.fromstring(resp.content)
  51. # init regex for yaml-parsing
  52. p = re.compile('({|,)([a-z]+):(")')
  53. # parse results
  54. for result in dom.xpath('//div[@class="dg_u"]'):
  55. link = result.xpath('./a')[0]
  56. # parse yaml-data (it is required to add a space, to make it parsable)
  57. yaml_data = load(p.sub(r'\1\2: \3', link.attrib.get('m')))
  58. title = link.attrib.get('t1')
  59. ihk = link.attrib.get('ihk')
  60. #url = 'http://' + link.attrib.get('t3')
  61. url = yaml_data.get('surl')
  62. img_src = yaml_data.get('imgurl')
  63. # append result
  64. results.append({'template': 'images.html',
  65. 'url': url,
  66. 'title': title,
  67. 'content': '',
  68. 'thumbnail_src': thumb_url.format(ihk=ihk),
  69. 'img_src': img_src})
  70. # TODO stop parsing if 10 images are found
  71. if len(results) >= 10:
  72. break
  73. # return results
  74. return results