.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
bing_news.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Bing-News: description see :py:obj:`searx.engines.bing`.
3
4.. hint::
5
6 Bing News is *different* in some ways!
7
8"""
9
10# pylint: disable=invalid-name
11
12from typing import TYPE_CHECKING
13from urllib.parse import urlencode
14
15from lxml import html
16
17from searx.utils import eval_xpath, extract_text, eval_xpath_list, eval_xpath_getindex
18from searx.enginelib.traits import EngineTraits
19from searx.engines.bing import set_bing_cookies
20
21if TYPE_CHECKING:
22 import logging
23
24 logger: logging.Logger
25
26traits: EngineTraits
27
28
29# about
30about = {
31 "website": 'https://www.bing.com/news',
32 "wikidata_id": 'Q2878637',
33 "official_api_documentation": 'https://www.microsoft.com/en-us/bing/apis/bing-news-search-api',
34 "use_official_api": False,
35 "require_api_key": False,
36 "results": 'RSS',
37}
38
39# engine dependent config
40categories = ['news']
41paging = True
42"""If go through the pages and there are actually no new results for another
43page, then bing returns the results from the last page again."""
44
45time_range_support = True
46time_map = {
47 'day': 'interval="4"',
48 'week': 'interval="7"',
49 'month': 'interval="9"',
50}
51"""A string '4' means *last hour*. We use *last hour* for ``day`` here since the
52difference of *last day* and *last week* in the result list is just marginally.
53Bing does not have news range ``year`` / we use ``month`` instead."""
54
55base_url = 'https://www.bing.com/news/infinitescrollajax'
56"""Bing (News) search URL"""
57
58
59def request(query, params):
60 """Assemble a Bing-News request."""
61
62 engine_region = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
63 engine_language = traits.get_language(params['searxng_locale'], 'en') # type: ignore
64 set_bing_cookies(params, engine_language, engine_region)
65
66 # build URL query
67 #
68 # example: https://www.bing.com/news/infinitescrollajax?q=london&first=1
69
70 page = int(params.get('pageno', 1)) - 1
71 query_params = {
72 'q': query,
73 'InfiniteScroll': 1,
74 # to simplify the page count lets use the default of 10 images per page
75 'first': page * 10 + 1,
76 'SFX': page,
77 'form': 'PTFTNR',
78 'setlang': engine_region.split('-')[0],
79 'cc': engine_region.split('-')[-1],
80 }
81
82 if params['time_range']:
83 query_params['qft'] = time_map.get(params['time_range'], 'interval="9"')
84
85 params['url'] = base_url + '?' + urlencode(query_params)
86
87 return params
88
89
90def response(resp):
91 """Get response from Bing-Video"""
92 results = []
93
94 if not resp.ok or not resp.text:
95 return results
96
97 dom = html.fromstring(resp.text)
98
99 for newsitem in eval_xpath_list(dom, '//div[contains(@class, "newsitem")]'):
100
101 link = eval_xpath_getindex(newsitem, './/a[@class="title"]', 0, None)
102 if link is None:
103 continue
104 url = link.attrib.get('href')
105 title = extract_text(link)
106 content = extract_text(eval_xpath(newsitem, './/div[@class="snippet"]'))
107
108 metadata = []
109 source = eval_xpath_getindex(newsitem, './/div[contains(@class, "source")]', 0, None)
110 if source is not None:
111 for item in (
112 eval_xpath_getindex(source, './/span[@aria-label]/@aria-label', 0, None),
113 # eval_xpath_getindex(source, './/a', 0, None),
114 # eval_xpath_getindex(source, './div/span', 3, None),
115 link.attrib.get('data-author'),
116 ):
117 if item is not None:
118 t = extract_text(item)
119 if t and t.strip():
120 metadata.append(t.strip())
121 metadata = ' | '.join(metadata)
122
123 thumbnail = None
124 imagelink = eval_xpath_getindex(newsitem, './/a[@class="imagelink"]//img', 0, None)
125 if imagelink is not None:
126 thumbnail = imagelink.attrib.get('src')
127 if not thumbnail.startswith("https://www.bing.com"):
128 thumbnail = 'https://www.bing.com/' + thumbnail
129
130 results.append(
131 {
132 'url': url,
133 'title': title,
134 'content': content,
135 'thumbnail': thumbnail,
136 'metadata': metadata,
137 }
138 )
139
140 return results
141
142
143def fetch_traits(engine_traits: EngineTraits):
144 """Fetch languages and regions from Bing-News."""
145 # pylint: disable=import-outside-toplevel
146
147 from searx.engines.bing import fetch_traits as _f
148
149 _f(engine_traits)
150
151 # fix market codes not known by bing news:
152
153 # In bing the market code 'zh-cn' exists, but there is no 'news' category in
154 # bing for this market. Alternatively we use the the market code from Honk
155 # Kong. Even if this is not correct, it is better than having no hits at
156 # all, or sending false queries to bing that could raise the suspicion of a
157 # bot.
158
159 # HINT: 'en-hk' is the region code it does not indicate the language en!!
160 engine_traits.regions['zh-CN'] = 'en-hk'
request(query, params)
Definition bing_news.py:59
fetch_traits(EngineTraits engine_traits)
Definition bing_news.py:143