bing_news.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing-News: description see :py:obj:`searx.engines.bing`.
  4. """
  5. # pylint: disable=invalid-name
  6. from typing import TYPE_CHECKING
  7. import uuid
  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. from searx.engines.bing import send_accept_language_header # pylint: disable=unused-import
  16. if TYPE_CHECKING:
  17. import logging
  18. logger: logging.Logger
  19. traits: EngineTraits
  20. # about
  21. about = {
  22. "website": 'https://www.bing.com/news',
  23. "wikidata_id": 'Q2878637',
  24. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-news-search-api',
  25. "use_official_api": False,
  26. "require_api_key": False,
  27. "results": 'RSS',
  28. }
  29. # engine dependent config
  30. categories = ['news']
  31. paging = True
  32. time_range_support = True
  33. time_map = {
  34. 'day': '4',
  35. 'week': '8',
  36. 'month': '9',
  37. }
  38. """A string '4' means *last hour*. We use *last hour* for ``day`` here since the
  39. difference of *last day* and *last week* in the result list is just marginally.
  40. """
  41. base_url = 'https://www.bing.com/news/infinitescrollajax'
  42. """Bing (News) search URL"""
  43. bing_traits_url = 'https://learn.microsoft.com/en-us/bing/search-apis/bing-news-search/reference/market-codes'
  44. """Bing (News) search API description"""
  45. mkt_alias = {
  46. 'zh': 'en-WW',
  47. 'zh-CN': 'en-WW',
  48. }
  49. """Bing News has an official market code 'zh-CN' but we won't get a result with
  50. this market code. For 'zh' and 'zh-CN' we better use the *Worldwide aggregate*
  51. market code (en-WW).
  52. """
  53. def request(query, params):
  54. """Assemble a Bing-News request."""
  55. sxng_locale = params['searxng_locale']
  56. engine_region = traits.get_region(mkt_alias.get(sxng_locale, sxng_locale), traits.all_locale)
  57. engine_language = traits.get_language(sxng_locale, 'en')
  58. SID = uuid.uuid1().hex.upper()
  59. set_bing_cookies(params, engine_language, engine_region, SID)
  60. # build URL query
  61. #
  62. # example: https://www.bing.com/news/infinitescrollajax?q=london&first=1
  63. query_params = {
  64. # fmt: off
  65. 'q': query,
  66. 'InfiniteScroll': 1,
  67. # to simplify the page count lets use the default of 10 images per page
  68. 'first' : (int(params.get('pageno', 1)) - 1) * 10 + 1,
  69. # fmt: on
  70. }
  71. if params['time_range']:
  72. # qft=interval:"7"
  73. query_params['qft'] = 'qft=interval="%s"' % time_map.get(params['time_range'], '9')
  74. params['url'] = base_url + '?' + urlencode(query_params)
  75. return params
  76. def response(resp):
  77. """Get response from Bing-Video"""
  78. results = []
  79. if not resp.ok or not resp.text:
  80. return results
  81. dom = html.fromstring(resp.text)
  82. for newsitem in dom.xpath('//div[contains(@class, "newsitem")]'):
  83. url = newsitem.xpath('./@url')[0]
  84. title = ' '.join(newsitem.xpath('.//div[@class="caption"]//a[@class="title"]/text()')).strip()
  85. content = ' '.join(newsitem.xpath('.//div[@class="snippet"]/text()')).strip()
  86. thumbnail = None
  87. author = newsitem.xpath('./@data-author')[0]
  88. metadata = ' '.join(newsitem.xpath('.//div[@class="source"]/span/text()')).strip()
  89. img_src = newsitem.xpath('.//a[@class="imagelink"]//img/@src')
  90. if img_src:
  91. thumbnail = 'https://www.bing.com/' + img_src[0]
  92. results.append(
  93. {
  94. 'url': url,
  95. 'title': title,
  96. 'content': content,
  97. 'img_src': thumbnail,
  98. 'author': author,
  99. 'metadata': metadata,
  100. }
  101. )
  102. return results
  103. def fetch_traits(engine_traits: EngineTraits):
  104. """Fetch languages and regions from Bing-News.
  105. The :py:obj:`description <searx.engines.bing_news.bing_traits_url>` of the
  106. first table says *"query parameter when calling the Video Search API."*
  107. .. thats why I use the 4. table "News Category API markets" for the
  108. ``xpath_market_codes``.
  109. """
  110. xpath_market_codes = '//table[4]/tbody/tr/td[3]'
  111. # xpath_country_codes = '//table[2]/tbody/tr/td[2]'
  112. xpath_language_codes = '//table[3]/tbody/tr/td[2]'
  113. _fetch_traits(engine_traits, bing_traits_url, xpath_language_codes, xpath_market_codes)