bing_news.py 4.2 KB

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