bing_images.py 3.7 KB

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