bing_images.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """
  2. Bing (Images)
  3. @website https://www.bing.com/images
  4. @provide-api yes (http://datamarket.azure.com/dataset/bing/search),
  5. max. 5000 query/month
  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. @todo currently there are up to 35 images receive per page,
  11. because bing does not parse count=10.
  12. limited response to 10 images
  13. """
  14. from urllib import urlencode
  15. from lxml import html
  16. from json import loads
  17. import re
  18. # engine dependent config
  19. categories = ['images']
  20. paging = True
  21. safesearch = True
  22. # search-url
  23. base_url = 'https://www.bing.com/'
  24. search_string = 'images/search?{query}&count=10&first={offset}'
  25. thumb_url = "https://www.bing.com/th?id={ihk}"
  26. # safesearch definitions
  27. safesearch_types = {2: 'STRICT',
  28. 1: 'DEMOTE',
  29. 0: 'OFF'}
  30. _quote_keys_regex = re.compile('({|,)([a-z][a-z0-9]*):(")', re.I | re.U)
  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.text)
  51. # parse results
  52. for result in dom.xpath('//div[@class="dg_u"]'):
  53. link = result.xpath('./a')[0]
  54. # parse json-data (it is required to add a space, to make it parsable)
  55. json_data = loads(_quote_keys_regex.sub(r'\1"\2": \3', link.attrib.get('m')))
  56. title = link.attrib.get('t1')
  57. ihk = link.attrib.get('ihk')
  58. # url = 'http://' + link.attrib.get('t3')
  59. url = json_data.get('surl')
  60. img_src = json_data.get('imgurl')
  61. # append result
  62. results.append({'template': 'images.html',
  63. 'url': url,
  64. 'title': title,
  65. 'content': '',
  66. 'thumbnail_src': thumb_url.format(ihk=ihk),
  67. 'img_src': img_src})
  68. # TODO stop parsing if 10 images are found
  69. if len(results) >= 10:
  70. break
  71. # return results
  72. return results