bing_news.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Bing (News)
  4. """
  5. from urllib.parse import (
  6. urlencode,
  7. urlparse,
  8. parse_qsl,
  9. quote,
  10. )
  11. from datetime import datetime
  12. from dateutil import parser
  13. from lxml import etree
  14. from lxml.etree import XPath
  15. from searx.utils import match_language, eval_xpath_getindex
  16. from searx.enginelib.traits import 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. time_range_support = True
  30. send_accept_language_header = True
  31. # search-url
  32. base_url = 'https://www.bing.com/'
  33. search_string = 'news/search?{query}&first={offset}&format=RSS'
  34. search_string_with_time = 'news/search?{query}&first={offset}&qft=interval%3d"{interval}"&format=RSS'
  35. time_range_dict = {'day': '7', 'week': '8', 'month': '9'}
  36. def url_cleanup(url_string):
  37. """remove click"""
  38. parsed_url = urlparse(url_string)
  39. if parsed_url.netloc == 'www.bing.com' and parsed_url.path == '/news/apiclick.aspx':
  40. query = dict(parse_qsl(parsed_url.query))
  41. url_string = query.get('url', None)
  42. return url_string
  43. def image_url_cleanup(url_string):
  44. """replace the http://*bing.com/th?id=... by https://www.bing.com/th?id=..."""
  45. parsed_url = urlparse(url_string)
  46. if parsed_url.netloc.endswith('bing.com') and parsed_url.path == '/th':
  47. query = dict(parse_qsl(parsed_url.query))
  48. url_string = "https://www.bing.com/th?id=" + quote(query.get('id'))
  49. return url_string
  50. def _get_url(query, language, offset, time_range):
  51. if time_range in time_range_dict:
  52. search_path = search_string_with_time.format(
  53. # fmt: off
  54. query = urlencode({
  55. 'q': query,
  56. 'setmkt': language
  57. }),
  58. offset = offset,
  59. interval = time_range_dict[time_range]
  60. # fmt: on
  61. )
  62. else:
  63. # e.g. setmkt=de-de&setlang=de
  64. search_path = search_string.format(
  65. # fmt: off
  66. query = urlencode({
  67. 'q': query,
  68. 'setmkt': language
  69. }),
  70. offset = offset
  71. # fmt: on
  72. )
  73. return base_url + search_path
  74. def request(query, params):
  75. if params['time_range'] and params['time_range'] not in time_range_dict:
  76. return params
  77. offset = (params['pageno'] - 1) * 10 + 1
  78. if params['language'] == 'all':
  79. language = 'en-US'
  80. else:
  81. language = match_language(params['language'], supported_languages, language_aliases)
  82. params['url'] = _get_url(query, language, offset, params['time_range'])
  83. return params
  84. def response(resp):
  85. results = []
  86. rss = etree.fromstring(resp.content)
  87. namespaces = rss.nsmap
  88. for item in rss.xpath('./channel/item'):
  89. # url / title / content
  90. url = url_cleanup(eval_xpath_getindex(item, './link/text()', 0, default=None))
  91. title = eval_xpath_getindex(item, './title/text()', 0, default=url)
  92. content = eval_xpath_getindex(item, './description/text()', 0, default='')
  93. # publishedDate
  94. publishedDate = eval_xpath_getindex(item, './pubDate/text()', 0, default=None)
  95. try:
  96. publishedDate = parser.parse(publishedDate, dayfirst=False)
  97. except TypeError:
  98. publishedDate = datetime.now()
  99. except ValueError:
  100. publishedDate = datetime.now()
  101. # thumbnail
  102. thumbnail = eval_xpath_getindex(item, XPath('./News:Image/text()', namespaces=namespaces), 0, default=None)
  103. if thumbnail is not None:
  104. thumbnail = image_url_cleanup(thumbnail)
  105. # append result
  106. if thumbnail is not None:
  107. results.append(
  108. {'url': url, 'title': title, 'publishedDate': publishedDate, 'content': content, 'img_src': thumbnail}
  109. )
  110. else:
  111. results.append({'url': url, 'title': title, 'publishedDate': publishedDate, 'content': content})
  112. return results
  113. def fetch_traits(engine_traits: EngineTraits):
  114. """Fetch languages and regions from Bing-News."""
  115. # pylint: disable=import-outside-toplevel
  116. from searx.engines.bing import _fetch_traits
  117. url = 'https://learn.microsoft.com/en-us/bing/search-apis/bing-news-search/reference/market-codes'
  118. # The description of the first table says "query parameter when calling the
  119. # Video Search API." .. thats why I use the 4. table "News Category API markets"
  120. xpath_market_codes = '//table[4]/tbody/tr/td[3]'
  121. # xpath_country_codes = '//table[2]/tbody/tr/td[2]'
  122. xpath_language_codes = '//table[3]/tbody/tr/td[2]'
  123. _fetch_traits(engine_traits, url, xpath_language_codes, xpath_market_codes)