bing_images.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 lxml import html
  15. from json import loads
  16. import re
  17. from searx.url_utils import urlencode
  18. # engine dependent config
  19. categories = ['images']
  20. paging = True
  21. safesearch = True
  22. time_range_support = True
  23. language_support = True
  24. supported_languages_url = 'https://www.bing.com/account/general'
  25. # search-url
  26. base_url = 'https://www.bing.com/'
  27. search_string = 'images/search?{query}&count=10&first={offset}'
  28. time_range_string = '&qft=+filterui:age-lt{interval}'
  29. time_range_dict = {'day': '1440',
  30. 'week': '10080',
  31. 'month': '43200',
  32. 'year': '525600'}
  33. # safesearch definitions
  34. safesearch_types = {2: 'STRICT',
  35. 1: 'DEMOTE',
  36. 0: 'OFF'}
  37. _quote_keys_regex = re.compile('({|,)([a-z][a-z0-9]*):(")', re.I | re.U)
  38. # get supported region code
  39. def get_region_code(lang, lang_list=None):
  40. region = None
  41. if lang in (lang_list or supported_languages):
  42. region = lang
  43. elif lang.startswith('no'):
  44. region = 'nb-NO'
  45. else:
  46. # try to get a supported country code with language
  47. lang = lang.split('-')[0]
  48. for lc in (lang_list or supported_languages):
  49. if lang == lc.split('-')[0]:
  50. region = lc
  51. break
  52. if region:
  53. return region.lower()
  54. else:
  55. return 'en-us'
  56. # do search-request
  57. def request(query, params):
  58. offset = (params['pageno'] - 1) * 10 + 1
  59. search_path = search_string.format(
  60. query=urlencode({'q': query}),
  61. offset=offset)
  62. language = get_region_code(params['language'])
  63. params['cookies']['SRCHHPGUSR'] = \
  64. 'ADLT=' + safesearch_types.get(params['safesearch'], 'DEMOTE')
  65. params['cookies']['_EDGE_S'] = 'mkt=' + language +\
  66. '&ui=' + language + '&F=1'
  67. params['url'] = base_url + search_path
  68. if params['time_range'] in time_range_dict:
  69. params['url'] += time_range_string.format(interval=time_range_dict[params['time_range']])
  70. return params
  71. # get response from search-request
  72. def response(resp):
  73. results = []
  74. dom = html.fromstring(resp.text)
  75. # parse results
  76. for result in dom.xpath('//div[@id="mmComponent_images_1"]/ul/li/div/div[@class="imgpt"]'):
  77. link = result.xpath('./a')[0]
  78. # TODO find actual title
  79. title = link.xpath('.//img/@alt')[0]
  80. # parse json-data (it is required to add a space, to make it parsable)
  81. json_data = loads(_quote_keys_regex.sub(r'\1"\2": \3', link.attrib.get('m')))
  82. url = json_data.get('purl')
  83. img_src = json_data.get('murl')
  84. thumb_json_data = loads(_quote_keys_regex.sub(r'\1"\2": \3', link.attrib.get('mad')))
  85. thumbnail = thumb_json_data.get('turl')
  86. # append result
  87. results.append({'template': 'images.html',
  88. 'url': url,
  89. 'title': title,
  90. 'content': '',
  91. 'thumbnail_src': thumbnail,
  92. 'img_src': img_src})
  93. # TODO stop parsing if 10 images are found
  94. # if len(results) >= 10:
  95. # break
  96. # return results
  97. return results
  98. # get supported languages from their site
  99. def _fetch_supported_languages(resp):
  100. supported_languages = []
  101. dom = html.fromstring(resp.text)
  102. regions_xpath = '//div[@id="region-section-content"]' \
  103. + '//ul[@class="b_vList"]/li/a/@href'
  104. regions = dom.xpath(regions_xpath)
  105. for region in regions:
  106. code = re.search('setmkt=[^\&]+', region).group()[7:]
  107. if code == 'nb-NO':
  108. code = 'no-NO'
  109. supported_languages.append(code)
  110. return supported_languages