.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
xpath.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""The XPath engine is a *generic* engine with which it is possible to configure
3engines in the settings.
4
5.. _XPath selector: https://quickref.me/xpath.html#xpath-selectors
6
7Configuration
8=============
9
10Request:
11
12- :py:obj:`search_url`
13- :py:obj:`lang_all`
14- :py:obj:`soft_max_redirects`
15- :py:obj:`method`
16- :py:obj:`request_body`
17- :py:obj:`cookies`
18- :py:obj:`headers`
19
20Paging:
21
22- :py:obj:`paging`
23- :py:obj:`page_size`
24- :py:obj:`first_page_num`
25
26Time Range:
27
28- :py:obj:`time_range_support`
29- :py:obj:`time_range_url`
30- :py:obj:`time_range_map`
31
32Safe-Search:
33
34- :py:obj:`safe_search_support`
35- :py:obj:`safe_search_map`
36
37Response:
38
39- :py:obj:`no_result_for_http_status`
40
41`XPath selector`_:
42
43- :py:obj:`results_xpath`
44- :py:obj:`url_xpath`
45- :py:obj:`title_xpath`
46- :py:obj:`content_xpath`
47- :py:obj:`thumbnail_xpath`
48- :py:obj:`suggestion_xpath`
49
50
51Example
52=======
53
54Here is a simple example of a XPath engine configured in the :ref:`settings
55engine` section, further read :ref:`engines-dev`.
56
57.. code:: yaml
58
59 - name : bitbucket
60 engine : xpath
61 paging : True
62 search_url : https://bitbucket.org/repo/all/{pageno}?name={query}
63 url_xpath : //article[@class="repo-summary"]//a[@class="repo-link"]/@href
64 title_xpath : //article[@class="repo-summary"]//a[@class="repo-link"]
65 content_xpath : //article[@class="repo-summary"]/p
66
67Implementations
68===============
69
70"""
71
72from urllib.parse import urlencode
73
74from lxml import html
75from searx.utils import extract_text, extract_url, eval_xpath, eval_xpath_list
76from searx.network import raise_for_httperror
77from searx.result_types import EngineResults
78
79search_url = None
80"""
81Search URL of the engine. Example::
82
83 https://example.org/?search={query}&page={pageno}{time_range}{safe_search}
84
85Replacements are:
86
87``{query}``:
88 Search terms from user.
89
90``{pageno}``:
91 Page number if engine supports paging :py:obj:`paging`
92
93``{lang}``:
94 ISO 639-1 language code (en, de, fr ..)
95
96``{time_range}``:
97 :py:obj:`URL parameter <time_range_url>` if engine :py:obj:`supports time
98 range <time_range_support>`. The value for the parameter is taken from
99 :py:obj:`time_range_map`.
100
101``{safe_search}``:
102 Safe-search :py:obj:`URL parameter <safe_search_map>` if engine
103 :py:obj:`supports safe-search <safe_search_support>`. The ``{safe_search}``
104 replacement is taken from the :py:obj:`safes_search_map`. Filter results::
105
106 0: none, 1: moderate, 2:strict
107
108 If not supported, the URL parameter is an empty string.
109
110"""
111
112lang_all = 'en'
113'''Replacement ``{lang}`` in :py:obj:`search_url` if language ``all`` is
114selected.
115'''
116
117no_result_for_http_status = []
118'''Return empty result for these HTTP status codes instead of throwing an error.
119
120.. code:: yaml
121
122 no_result_for_http_status: []
123'''
124
125soft_max_redirects = 0
126'''Maximum redirects, soft limit. Record an error but don't stop the engine'''
127
128results_xpath = ''
129'''`XPath selector`_ for the list of result items'''
130
131url_xpath = None
132'''`XPath selector`_ of result's ``url``.'''
133
134content_xpath = None
135'''`XPath selector`_ of result's ``content``.'''
136
137title_xpath = None
138'''`XPath selector`_ of result's ``title``.'''
139
140thumbnail_xpath = False
141'''`XPath selector`_ of result's ``thumbnail``.'''
142
143suggestion_xpath = ''
144'''`XPath selector`_ of result's ``suggestion``.'''
145
146cached_xpath = ''
147cached_url = ''
148
149cookies = {}
150'''Some engines might offer different result based on cookies.
151Possible use-case: To set safesearch cookie.'''
152
153headers = {}
154'''Some engines might offer different result based headers. Possible use-case:
155To set header to moderate.'''
156
157method = 'GET'
158'''Some engines might require to do POST requests for search.'''
159
160request_body = ''
161'''The body of the request. This can only be used if different :py:obj:`method`
162is set, e.g. ``POST``. For formatting see the documentation of :py:obj:`search_url`::
163
164 search={query}&page={pageno}{time_range}{safe_search}
165'''
166
167paging = False
168'''Engine supports paging [True or False].'''
169
170page_size = 1
171'''Number of results on each page. Only needed if the site requires not a page
172number, but an offset.'''
173
174first_page_num = 1
175'''Number of the first page (usually 0 or 1).'''
176
177time_range_support = False
178'''Engine supports search time range.'''
179
180time_range_url = '&hours={time_range_val}'
181'''Time range URL parameter in the in :py:obj:`search_url`. If no time range is
182requested by the user, the URL parameter is an empty string. The
183``{time_range_val}`` replacement is taken from the :py:obj:`time_range_map`.
184
185.. code:: yaml
186
187 time_range_url : '&days={time_range_val}'
188'''
189
190time_range_map = {
191 'day': 24,
192 'week': 24 * 7,
193 'month': 24 * 30,
194 'year': 24 * 365,
195}
196'''Maps time range value from user to ``{time_range_val}`` in
197:py:obj:`time_range_url`.
198
199.. code:: yaml
200
201 time_range_map:
202 day: 1
203 week: 7
204 month: 30
205 year: 365
206'''
207
208safe_search_support = False
209'''Engine supports safe-search.'''
210
211safe_search_map = {0: '&filter=none', 1: '&filter=moderate', 2: '&filter=strict'}
212'''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
213
214.. code:: yaml
215
216 safesearch: true
217 safes_search_map:
218 0: '&filter=none'
219 1: '&filter=moderate'
220 2: '&filter=strict'
221
222'''
223
224
225def request(query, params):
226 '''Build request parameters (see :ref:`engine request`).'''
227 lang = lang_all
228 if params['language'] != 'all':
229 lang = params['language'][:2]
230
231 time_range = ''
232 if params.get('time_range'):
233 time_range_val = time_range_map.get(params.get('time_range'))
234 time_range = time_range_url.format(time_range_val=time_range_val)
235
236 safe_search = ''
237 if params['safesearch']:
238 safe_search = safe_search_map[params['safesearch']]
239
240 fargs = {
241 'query': urlencode({'q': query})[2:],
242 'lang': lang,
243 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
244 'time_range': time_range,
245 'safe_search': safe_search,
246 }
247
248 params['cookies'].update(cookies)
249 params['headers'].update(headers)
250
251 params['url'] = search_url.format(**fargs)
252 params['method'] = method
253
254 if request_body:
255 # don't url-encode the query if it's in the request body
256 fargs['query'] = query
257 params['data'] = request_body.format(**fargs)
258
259 params['soft_max_redirects'] = soft_max_redirects
260 params['raise_for_httperror'] = False
261
262 return params
263
264
265def response(resp) -> EngineResults: # pylint: disable=too-many-branches
266 """Scrap *results* from the response (see :ref:`result types`)."""
267 results = EngineResults()
268
269 if no_result_for_http_status and resp.status_code in no_result_for_http_status:
270 return results
271
272 raise_for_httperror(resp)
273
274 if not resp.text:
275 return results
276
277 dom = html.fromstring(resp.text)
278 is_onion = 'onions' in categories
279
280 if results_xpath:
281 for result in eval_xpath_list(dom, results_xpath):
282
283 url = extract_url(eval_xpath_list(result, url_xpath, min_len=1), search_url)
284 title = extract_text(eval_xpath_list(result, title_xpath, min_len=1))
285 content = extract_text(eval_xpath_list(result, content_xpath))
286 tmp_result = {'url': url, 'title': title, 'content': content}
287
288 # add thumbnail if available
289 if thumbnail_xpath:
290 thumbnail_xpath_result = eval_xpath_list(result, thumbnail_xpath)
291 if len(thumbnail_xpath_result) > 0:
292 tmp_result['thumbnail'] = extract_url(thumbnail_xpath_result, search_url)
293
294 # add alternative cached url if available
295 if cached_xpath:
296 tmp_result['cached_url'] = cached_url + extract_text(eval_xpath_list(result, cached_xpath, min_len=1))
297
298 if is_onion:
299 tmp_result['is_onion'] = True
300
301 results.append(tmp_result)
302
303 else:
304 if cached_xpath:
305 for url, title, content, cached in zip(
306 (extract_url(x, search_url) for x in eval_xpath_list(dom, url_xpath)),
307 map(extract_text, eval_xpath_list(dom, title_xpath)),
308 map(extract_text, eval_xpath_list(dom, content_xpath)),
309 map(extract_text, eval_xpath_list(dom, cached_xpath)),
310 ):
311 results.append(
312 {
313 'url': url,
314 'title': title,
315 'content': content,
316 'cached_url': cached_url + cached,
317 'is_onion': is_onion,
318 }
319 )
320 else:
321 for url, title, content in zip(
322 (extract_url(x, search_url) for x in eval_xpath_list(dom, url_xpath)),
323 map(extract_text, eval_xpath_list(dom, title_xpath)),
324 map(extract_text, eval_xpath_list(dom, content_xpath)),
325 ):
326 results.append({'url': url, 'title': title, 'content': content, 'is_onion': is_onion})
327
328 if suggestion_xpath:
329 for suggestion in eval_xpath(dom, suggestion_xpath):
330 results.append({'suggestion': extract_text(suggestion)})
331
332 logger.debug("found %s results", len(results))
333 return results
EngineResults response(resp)
Definition xpath.py:265
request(query, params)
Definition xpath.py:225