bing_images.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing-Images: description see :py:obj:`searx.engines.bing`.
  4. """
  5. # pylint: disable=invalid-name
  6. from typing import TYPE_CHECKING
  7. import json
  8. from urllib.parse import urlencode
  9. from lxml import html
  10. from searx.enginelib.traits import EngineTraits
  11. from searx.engines.bing import (
  12. set_bing_cookies,
  13. _fetch_traits,
  14. )
  15. if TYPE_CHECKING:
  16. import logging
  17. logger: logging.Logger
  18. traits: EngineTraits
  19. # about
  20. about = {
  21. "website": 'https://www.bing.com/images',
  22. "wikidata_id": 'Q182496',
  23. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-image-search-api',
  24. "use_official_api": False,
  25. "require_api_key": False,
  26. "results": 'HTML',
  27. }
  28. # engine dependent config
  29. categories = ['images', 'web']
  30. paging = True
  31. safesearch = True
  32. time_range_support = True
  33. base_url = 'https://www.bing.com/images/async'
  34. """Bing (Images) search URL"""
  35. bing_traits_url = 'https://learn.microsoft.com/en-us/bing/search-apis/bing-image-search/reference/market-codes'
  36. """Bing (Images) search API description"""
  37. time_map = {
  38. # fmt: off
  39. 'day': 60 * 24,
  40. 'week': 60 * 24 * 7,
  41. 'month': 60 * 24 * 31,
  42. 'year': 60 * 24 * 365,
  43. # fmt: on
  44. }
  45. def request(query, params):
  46. """Assemble a Bing-Image request."""
  47. engine_region = traits.get_region(params['searxng_locale'], 'en-us')
  48. engine_language = traits.get_language(params['searxng_locale'], 'en-us')
  49. set_bing_cookies(params, engine_language, engine_region)
  50. # build URL query
  51. # - example: https://www.bing.com/images/async?q=foo&first=155&count=35
  52. query_params = {
  53. # fmt: off
  54. 'q': query,
  55. 'async' : 'content',
  56. # to simplify the page count lets use the default of 35 images per page
  57. 'first' : (int(params.get('pageno', 1)) - 1) * 35 + 1,
  58. 'count' : 35,
  59. # fmt: on
  60. }
  61. # time range
  62. # - example: one year (525600 minutes) 'qft=+filterui:age-lt525600'
  63. if params['time_range']:
  64. query_params['qft'] = 'filterui:age-lt%s' % time_map[params['time_range']]
  65. params['url'] = base_url + '?' + urlencode(query_params)
  66. return params
  67. def response(resp):
  68. """Get response from Bing-Images"""
  69. results = []
  70. dom = html.fromstring(resp.text)
  71. for result in dom.xpath('//ul[contains(@class, "dgControl_list")]/li'):
  72. metadata = result.xpath('.//a[@class="iusc"]/@m')
  73. if not metadata:
  74. continue
  75. metadata = json.loads(result.xpath('.//a[@class="iusc"]/@m')[0])
  76. title = ' '.join(result.xpath('.//div[@class="infnmpt"]//a/text()')).strip()
  77. img_format = ' '.join(result.xpath('.//div[@class="imgpt"]/div/span/text()')).strip()
  78. source = ' '.join(result.xpath('.//div[@class="imgpt"]//div[@class="lnkw"]//a/text()')).strip()
  79. results.append(
  80. {
  81. 'template': 'images.html',
  82. 'url': metadata['purl'],
  83. 'thumbnail_src': metadata['turl'],
  84. 'img_src': metadata['murl'],
  85. 'content': metadata['desc'],
  86. 'title': title,
  87. 'source': source,
  88. 'img_format': img_format,
  89. }
  90. )
  91. return results
  92. def fetch_traits(engine_traits: EngineTraits):
  93. """Fetch languages and regions from Bing-News."""
  94. xpath_market_codes = '//table[1]/tbody/tr/td[3]'
  95. # xpath_country_codes = '//table[2]/tbody/tr/td[2]'
  96. xpath_language_codes = '//table[3]/tbody/tr/td[2]'
  97. _fetch_traits(engine_traits, bing_traits_url, xpath_language_codes, xpath_market_codes)