.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
77
78search_url = None
79"""
80Search URL of the engine. Example::
81
82 https://example.org/?search={query}&page={pageno}{time_range}{safe_search}
83
84Replacements are:
85
86``{query}``:
87 Search terms from user.
88
89``{pageno}``:
90 Page number if engine supports paging :py:obj:`paging`
91
92``{lang}``:
93 ISO 639-1 language code (en, de, fr ..)
94
95``{time_range}``:
96 :py:obj:`URL parameter <time_range_url>` if engine :py:obj:`supports time
97 range <time_range_support>`. The value for the parameter is taken from
98 :py:obj:`time_range_map`.
99
100``{safe_search}``:
101 Safe-search :py:obj:`URL parameter <safe_search_map>` if engine
102 :py:obj:`supports safe-search <safe_search_support>`. The ``{safe_search}``
103 replacement is taken from the :py:obj:`safes_search_map`. Filter results::
104
105 0: none, 1: moderate, 2:strict
106
107 If not supported, the URL parameter is an empty string.
108
109"""
110
111lang_all = 'en'
112'''Replacement ``{lang}`` in :py:obj:`search_url` if language ``all`` is
113selected.
114'''
115
116no_result_for_http_status = []
117'''Return empty result for these HTTP status codes instead of throwing an error.
118
119.. code:: yaml
120
121 no_result_for_http_status: []
122'''
123
124soft_max_redirects = 0
125'''Maximum redirects, soft limit. Record an error but don't stop the engine'''
126
127results_xpath = ''
128'''`XPath selector`_ for the list of result items'''
129
130url_xpath = None
131'''`XPath selector`_ of result's ``url``.'''
132
133content_xpath = None
134'''`XPath selector`_ of result's ``content``.'''
135
136title_xpath = None
137'''`XPath selector`_ of result's ``title``.'''
138
139thumbnail_xpath = False
140'''`XPath selector`_ of result's ``thumbnail``.'''
141
142suggestion_xpath = ''
143'''`XPath selector`_ of result's ``suggestion``.'''
144
145cached_xpath = ''
146cached_url = ''
147
148cookies = {}
149'''Some engines might offer different result based on cookies.
150Possible use-case: To set safesearch cookie.'''
151
152headers = {}
153'''Some engines might offer different result based headers. Possible use-case:
154To set header to moderate.'''
155
156method = 'GET'
157'''Some engines might require to do POST requests for search.'''
158
159request_body = ''
160'''The body of the request. This can only be used if different :py:obj:`method`
161is set, e.g. ``POST``. For formatting see the documentation of :py:obj:`search_url`::
162
163 search={query}&page={pageno}{time_range}{safe_search}
164'''
165
166paging = False
167'''Engine supports paging [True or False].'''
168
169page_size = 1
170'''Number of results on each page. Only needed if the site requires not a page
171number, but an offset.'''
172
173first_page_num = 1
174'''Number of the first page (usually 0 or 1).'''
175
176time_range_support = False
177'''Engine supports search time range.'''
178
179time_range_url = '&hours={time_range_val}'
180'''Time range URL parameter in the in :py:obj:`search_url`. If no time range is
181requested by the user, the URL parameter is an empty string. The
182``{time_range_val}`` replacement is taken from the :py:obj:`time_range_map`.
183
184.. code:: yaml
185
186 time_range_url : '&days={time_range_val}'
187'''
188
189time_range_map = {
190 'day': 24,
191 'week': 24 * 7,
192 'month': 24 * 30,
193 'year': 24 * 365,
194}
195'''Maps time range value from user to ``{time_range_val}`` in
196:py:obj:`time_range_url`.
197
198.. code:: yaml
199
200 time_range_map:
201 day: 1
202 week: 7
203 month: 30
204 year: 365
205'''
206
207safe_search_support = False
208'''Engine supports safe-search.'''
209
210safe_search_map = {0: '&filter=none', 1: '&filter=moderate', 2: '&filter=strict'}
211'''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
212
213.. code:: yaml
214
215 safesearch: true
216 safes_search_map:
217 0: '&filter=none'
218 1: '&filter=moderate'
219 2: '&filter=strict'
220
221'''
222
223
224def request(query, params):
225 '''Build request parameters (see :ref:`engine request`).'''
226 lang = lang_all
227 if params['language'] != 'all':
228 lang = params['language'][:2]
229
230 time_range = ''
231 if params.get('time_range'):
232 time_range_val = time_range_map.get(params.get('time_range'))
233 time_range = time_range_url.format(time_range_val=time_range_val)
234
235 safe_search = ''
236 if params['safesearch']:
237 safe_search = safe_search_map[params['safesearch']]
238
239 fargs = {
240 'query': urlencode({'q': query})[2:],
241 'lang': lang,
242 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
243 'time_range': time_range,
244 'safe_search': safe_search,
245 }
246
247 params['cookies'].update(cookies)
248 params['headers'].update(headers)
249
250 params['url'] = search_url.format(**fargs)
251 params['method'] = method
252
253 if request_body:
254 # don't url-encode the query if it's in the request body
255 fargs['query'] = query
256 params['data'] = request_body.format(**fargs)
257
258 params['soft_max_redirects'] = soft_max_redirects
259 params['raise_for_httperror'] = False
260
261 return params
262
263
264def response(resp): # pylint: disable=too-many-branches
265 '''Scrap *results* from the response (see :ref:`engine results`).'''
266 if no_result_for_http_status and resp.status_code in no_result_for_http_status:
267 return []
268
269 raise_for_httperror(resp)
270
271 results = []
272
273 if not resp.text:
274 return results
275
276 dom = html.fromstring(resp.text)
277 is_onion = 'onions' in categories
278
279 if results_xpath:
280 for result in eval_xpath_list(dom, results_xpath):
281
282 url = extract_url(eval_xpath_list(result, url_xpath, min_len=1), search_url)
283 title = extract_text(eval_xpath_list(result, title_xpath, min_len=1))
284 content = extract_text(eval_xpath_list(result, content_xpath))
285 tmp_result = {'url': url, 'title': title, 'content': content}
286
287 # add thumbnail if available
288 if thumbnail_xpath:
289 thumbnail_xpath_result = eval_xpath_list(result, thumbnail_xpath)
290 if len(thumbnail_xpath_result) > 0:
291 tmp_result['thumbnail'] = extract_url(thumbnail_xpath_result, search_url)
292
293 # add alternative cached url if available
294 if cached_xpath:
295 tmp_result['cached_url'] = cached_url + extract_text(eval_xpath_list(result, cached_xpath, min_len=1))
296
297 if is_onion:
298 tmp_result['is_onion'] = True
299
300 results.append(tmp_result)
301
302 else:
303 if cached_xpath:
304 for url, title, content, cached in zip(
305 (extract_url(x, search_url) for x in eval_xpath_list(dom, url_xpath)),
306 map(extract_text, eval_xpath_list(dom, title_xpath)),
307 map(extract_text, eval_xpath_list(dom, content_xpath)),
308 map(extract_text, eval_xpath_list(dom, cached_xpath)),
309 ):
310 results.append(
311 {
312 'url': url,
313 'title': title,
314 'content': content,
315 'cached_url': cached_url + cached,
316 'is_onion': is_onion,
317 }
318 )
319 else:
320 for url, title, content in zip(
321 (extract_url(x, search_url) for x in eval_xpath_list(dom, url_xpath)),
322 map(extract_text, eval_xpath_list(dom, title_xpath)),
323 map(extract_text, eval_xpath_list(dom, content_xpath)),
324 ):
325 results.append({'url': url, 'title': title, 'content': content, 'is_onion': is_onion})
326
327 if suggestion_xpath:
328 for suggestion in eval_xpath(dom, suggestion_xpath):
329 results.append({'suggestion': extract_text(suggestion)})
330
331 logger.debug("found %s results", len(results))
332 return results
request(query, params)
Definition xpath.py:224