bing_news.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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.engines.bing import ( # pylint: disable=unused-import
  17. language_aliases,
  18. _fetch_supported_languages,
  19. fetch_traits,
  20. supported_languages_url,
  21. )
  22. # about
  23. about = {
  24. "website": 'https://www.bing.com/news',
  25. "wikidata_id": 'Q2878637',
  26. "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-news-search-api',
  27. "use_official_api": False,
  28. "require_api_key": False,
  29. "results": 'RSS',
  30. }
  31. # engine dependent config
  32. categories = ['news']
  33. paging = True
  34. time_range_support = True
  35. send_accept_language_header = True
  36. # search-url
  37. base_url = 'https://www.bing.com/'
  38. search_string = 'news/search?{query}&first={offset}&format=RSS'
  39. search_string_with_time = 'news/search?{query}&first={offset}&qft=interval%3d"{interval}"&format=RSS'
  40. time_range_dict = {'day': '7', 'week': '8', 'month': '9'}
  41. def url_cleanup(url_string):
  42. """remove click"""
  43. parsed_url = urlparse(url_string)
  44. if parsed_url.netloc == 'www.bing.com' and parsed_url.path == '/news/apiclick.aspx':
  45. query = dict(parse_qsl(parsed_url.query))
  46. url_string = query.get('url', None)
  47. return url_string
  48. def image_url_cleanup(url_string):
  49. """replace the http://*bing.com/th?id=... by https://www.bing.com/th?id=..."""
  50. parsed_url = urlparse(url_string)
  51. if parsed_url.netloc.endswith('bing.com') and parsed_url.path == '/th':
  52. query = dict(parse_qsl(parsed_url.query))
  53. url_string = "https://www.bing.com/th?id=" + quote(query.get('id'))
  54. return url_string
  55. def _get_url(query, language, offset, time_range):
  56. if time_range in time_range_dict:
  57. search_path = search_string_with_time.format(
  58. # fmt: off
  59. query = urlencode({
  60. 'q': query,
  61. 'setmkt': language
  62. }),
  63. offset = offset,
  64. interval = time_range_dict[time_range]
  65. # fmt: on
  66. )
  67. else:
  68. # e.g. setmkt=de-de&setlang=de
  69. search_path = search_string.format(
  70. # fmt: off
  71. query = urlencode({
  72. 'q': query,
  73. 'setmkt': language
  74. }),
  75. offset = offset
  76. # fmt: on
  77. )
  78. return base_url + search_path
  79. def request(query, params):
  80. if params['time_range'] and params['time_range'] not in time_range_dict:
  81. return params
  82. offset = (params['pageno'] - 1) * 10 + 1
  83. if params['language'] == 'all':
  84. language = 'en-US'
  85. else:
  86. language = match_language(params['language'], supported_languages, language_aliases)
  87. params['url'] = _get_url(query, language, offset, params['time_range'])
  88. return params
  89. def response(resp):
  90. results = []
  91. rss = etree.fromstring(resp.content)
  92. namespaces = rss.nsmap
  93. for item in rss.xpath('./channel/item'):
  94. # url / title / content
  95. url = url_cleanup(eval_xpath_getindex(item, './link/text()', 0, default=None))
  96. title = eval_xpath_getindex(item, './title/text()', 0, default=url)
  97. content = eval_xpath_getindex(item, './description/text()', 0, default='')
  98. # publishedDate
  99. publishedDate = eval_xpath_getindex(item, './pubDate/text()', 0, default=None)
  100. try:
  101. publishedDate = parser.parse(publishedDate, dayfirst=False)
  102. except TypeError:
  103. publishedDate = datetime.now()
  104. except ValueError:
  105. publishedDate = datetime.now()
  106. # thumbnail
  107. thumbnail = eval_xpath_getindex(item, XPath('./News:Image/text()', namespaces=namespaces), 0, default=None)
  108. if thumbnail is not None:
  109. thumbnail = image_url_cleanup(thumbnail)
  110. # append result
  111. if thumbnail is not None:
  112. results.append(
  113. {'url': url, 'title': title, 'publishedDate': publishedDate, 'content': content, 'img_src': thumbnail}
  114. )
  115. else:
  116. results.append({'url': url, 'title': title, 'publishedDate': publishedDate, 'content': content})
  117. return results