bing_news.py 4.8 KB

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