bing_news.py 4.3 KB

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