bing_news.py 4.2 KB

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