bing_news.py 4.2 KB

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