bing_news.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Bing-News: description see :py:obj:`searx.engines.bing`.
  3. .. hint::
  4. Bing News is *different* in some ways!
  5. """
  6. # pylint: disable=invalid-name
  7. from typing import TYPE_CHECKING
  8. from urllib.parse import urlencode
  9. from lxml import html
  10. from searx.utils import eval_xpath, extract_text, eval_xpath_list, eval_xpath_getindex
  11. from searx.enginelib.traits import EngineTraits
  12. from searx.engines.bing import set_bing_cookies
  13. if TYPE_CHECKING:
  14. import logging
  15. logger: logging.Logger
  16. traits: EngineTraits
  17. # about
  18. about = {
  19. "website": 'https://www.bing.com/news',
  20. "wikidata_id": 'Q2878637',
  21. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-news-search-api',
  22. "use_official_api": False,
  23. "require_api_key": False,
  24. "results": 'RSS',
  25. }
  26. # engine dependent config
  27. categories = ['news']
  28. paging = True
  29. """If go through the pages and there are actually no new results for another
  30. page, then bing returns the results from the last page again."""
  31. time_range_support = True
  32. time_map = {
  33. 'day': 'interval="4"',
  34. 'week': 'interval="7"',
  35. 'month': 'interval="9"',
  36. }
  37. """A string '4' means *last hour*. We use *last hour* for ``day`` here since the
  38. difference of *last day* and *last week* in the result list is just marginally.
  39. Bing does not have news range ``year`` / we use ``month`` instead."""
  40. base_url = 'https://www.bing.com/news/infinitescrollajax'
  41. """Bing (News) search URL"""
  42. def request(query, params):
  43. """Assemble a Bing-News request."""
  44. engine_region = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
  45. engine_language = traits.get_language(params['searxng_locale'], 'en') # type: ignore
  46. set_bing_cookies(params, engine_language, engine_region)
  47. # build URL query
  48. #
  49. # example: https://www.bing.com/news/infinitescrollajax?q=london&first=1
  50. page = int(params.get('pageno', 1)) - 1
  51. query_params = {
  52. 'q': query,
  53. 'InfiniteScroll': 1,
  54. # to simplify the page count lets use the default of 10 images per page
  55. 'first': page * 10 + 1,
  56. 'SFX': page,
  57. 'form': 'PTFTNR',
  58. 'setlang': engine_region.split('-')[0],
  59. 'cc': engine_region.split('-')[-1],
  60. }
  61. if params['time_range']:
  62. query_params['qft'] = time_map.get(params['time_range'], 'interval="9"')
  63. params['url'] = base_url + '?' + urlencode(query_params)
  64. return params
  65. def response(resp):
  66. """Get response from Bing-Video"""
  67. results = []
  68. if not resp.ok or not resp.text:
  69. return results
  70. dom = html.fromstring(resp.text)
  71. for newsitem in eval_xpath_list(dom, '//div[contains(@class, "newsitem")]'):
  72. link = eval_xpath_getindex(newsitem, './/a[@class="title"]', 0, None)
  73. if link is None:
  74. continue
  75. url = link.attrib.get('href')
  76. title = extract_text(link)
  77. content = extract_text(eval_xpath(newsitem, './/div[@class="snippet"]'))
  78. metadata = []
  79. source = eval_xpath_getindex(newsitem, './/div[contains(@class, "source")]', 0, None)
  80. if source is not None:
  81. for item in (
  82. eval_xpath_getindex(source, './/span[@aria-label]/@aria-label', 0, None),
  83. # eval_xpath_getindex(source, './/a', 0, None),
  84. # eval_xpath_getindex(source, './div/span', 3, None),
  85. link.attrib.get('data-author'),
  86. ):
  87. if item is not None:
  88. t = extract_text(item)
  89. if t and t.strip():
  90. metadata.append(t.strip())
  91. metadata = ' | '.join(metadata)
  92. thumbnail = None
  93. imagelink = eval_xpath_getindex(newsitem, './/a[@class="imagelink"]//img', 0, None)
  94. if imagelink is not None:
  95. thumbnail = imagelink.attrib.get('src')
  96. if not thumbnail.startswith("https://www.bing.com"):
  97. thumbnail = 'https://www.bing.com/' + thumbnail
  98. results.append(
  99. {
  100. 'url': url,
  101. 'title': title,
  102. 'content': content,
  103. 'thumbnail': thumbnail,
  104. 'metadata': metadata,
  105. }
  106. )
  107. return results
  108. def fetch_traits(engine_traits: EngineTraits):
  109. """Fetch languages and regions from Bing-News."""
  110. # pylint: disable=import-outside-toplevel
  111. from searx.engines.bing import fetch_traits as _f
  112. _f(engine_traits)
  113. # fix market codes not known by bing news:
  114. # In bing the market code 'zh-cn' exists, but there is no 'news' category in
  115. # bing for this market. Alternatively we use the the market code from Honk
  116. # Kong. Even if this is not correct, it is better than having no hits at
  117. # all, or sending false queries to bing that could raise the suspicion of a
  118. # bot.
  119. # HINT: 'en-hk' is the region code it does not indicate the language en!!
  120. engine_traits.regions['zh-CN'] = 'en-hk'