xpath.py 7.5 KB

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