xpath.py 7.3 KB

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