bing_images.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing (Images)
  4. """
  5. from json import loads
  6. from urllib.parse import urlencode
  7. from lxml import html
  8. from searx.utils import match_language
  9. from searx.enginelib.traits import EngineTraits
  10. # about
  11. about = {
  12. "website": 'https://www.bing.com/images',
  13. "wikidata_id": 'Q182496',
  14. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-image-search-api',
  15. "use_official_api": False,
  16. "require_api_key": False,
  17. "results": 'HTML',
  18. }
  19. # engine dependent config
  20. categories = ['images', 'web']
  21. paging = True
  22. safesearch = True
  23. time_range_support = True
  24. send_accept_language_header = True
  25. supported_languages_url = 'https://www.bing.com/account/general'
  26. number_of_results = 28
  27. # search-url
  28. base_url = 'https://www.bing.com/'
  29. search_string = (
  30. # fmt: off
  31. 'images/search'
  32. '?{query}'
  33. '&count={count}'
  34. '&first={first}'
  35. '&tsc=ImageHoverTitle'
  36. # fmt: on
  37. )
  38. time_range_string = '&qft=+filterui:age-lt{interval}'
  39. time_range_dict = {'day': '1440', 'week': '10080', 'month': '43200', 'year': '525600'}
  40. # safesearch definitions
  41. safesearch_types = {2: 'STRICT', 1: 'DEMOTE', 0: 'OFF'}
  42. # do search-request
  43. def request(query, params):
  44. offset = ((params['pageno'] - 1) * number_of_results) + 1
  45. search_path = search_string.format(query=urlencode({'q': query}), count=number_of_results, first=offset)
  46. language = match_language(params['language'], supported_languages, language_aliases).lower()
  47. params['cookies']['SRCHHPGUSR'] = 'ADLT=' + safesearch_types.get(params['safesearch'], 'DEMOTE')
  48. params['cookies']['_EDGE_S'] = 'mkt=' + language + '&ui=' + language + '&F=1'
  49. params['url'] = base_url + search_path
  50. if params['time_range'] in time_range_dict:
  51. params['url'] += time_range_string.format(interval=time_range_dict[params['time_range']])
  52. return params
  53. # get response from search-request
  54. def response(resp):
  55. results = []
  56. dom = html.fromstring(resp.text)
  57. # parse results
  58. for result in dom.xpath('//div[@class="imgpt"]'):
  59. img_format = result.xpath('./div[contains(@class, "img_info")]/span/text()')[0]
  60. # Microsoft seems to experiment with this code so don't make the path too specific,
  61. # just catch the text section for the first anchor in img_info assuming this to be
  62. # the originating site.
  63. source = result.xpath('./div[contains(@class, "img_info")]//a/text()')[0]
  64. m = loads(result.xpath('./a/@m')[0])
  65. # strip 'Unicode private use area' highlighting, they render to Tux
  66. # the Linux penguin and a standing diamond on my machine...
  67. title = m.get('t', '').replace('\ue000', '').replace('\ue001', '')
  68. results.append(
  69. {
  70. 'template': 'images.html',
  71. 'url': m['purl'],
  72. 'thumbnail_src': m['turl'],
  73. 'img_src': m['murl'],
  74. 'content': '',
  75. 'title': title,
  76. 'source': source,
  77. 'img_format': img_format,
  78. }
  79. )
  80. return results
  81. def fetch_traits(engine_traits: EngineTraits):
  82. """Fetch languages and regions from Bing-News."""
  83. # pylint: disable=import-outside-toplevel
  84. from searx.engines.bing import _fetch_traits
  85. url = 'https://learn.microsoft.com/en-us/bing/search-apis/bing-news-search/reference/market-codes'
  86. xpath_market_codes = '//table[1]/tbody/tr/td[3]'
  87. # xpath_country_codes = '//table[2]/tbody/tr/td[2]'
  88. xpath_language_codes = '//table[3]/tbody/tr/td[2]'
  89. _fetch_traits(engine_traits, url, xpath_language_codes, xpath_market_codes)