xpath.py 7.1 KB

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