xpath.py 8.9 KB

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