xpath.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. soft_max_redirects = 0
  46. '''Maximum redirects, soft limit. Record an error but don't stop the engine'''
  47. results_xpath = ''
  48. '''XPath selector for the list of result items'''
  49. url_xpath = None
  50. '''XPath selector of result's ``url``.'''
  51. content_xpath = None
  52. '''XPath selector of result's ``content``.'''
  53. title_xpath = None
  54. '''XPath selector of result's ``title``.'''
  55. thumbnail_xpath = False
  56. '''XPath selector of result's ``img_src``.'''
  57. suggestion_xpath = ''
  58. '''XPath selector of result's ``suggestion``.'''
  59. cached_xpath = ''
  60. cached_url = ''
  61. paging = False
  62. '''Engine supports paging [True or False].'''
  63. page_size = 1
  64. '''Number of results on each page. Only needed if the site requires not a page
  65. number, but an offset.'''
  66. first_page_num = 1
  67. '''Number of the first page (usually 0 or 1).'''
  68. time_range_support = False
  69. '''Engine supports search time range.'''
  70. time_range_url = '&hours={time_range_val}'
  71. '''Time range URL parameter in the in :py:obj:`search_url`. If no time range is
  72. requested by the user, the URL paramter is an empty string. The
  73. ``{time_range_val}`` replacement is taken from the :py:obj:`time_range_map`.
  74. .. code:: yaml
  75. time_range_url : '&days={time_range_val}'
  76. '''
  77. time_range_map = {
  78. 'day': 24,
  79. 'week': 24 * 7,
  80. 'month': 24 * 30,
  81. 'year': 24 * 365,
  82. }
  83. '''Maps time range value from user to ``{time_range_val}`` in
  84. :py:obj:`time_range_url`.
  85. .. code:: yaml
  86. time_range_map:
  87. day: 1
  88. week: 7
  89. month: 30
  90. year: 365
  91. '''
  92. safe_search_support = False
  93. '''Engine supports safe-search.'''
  94. safe_search_map = {0: '&filter=none', 1: '&filter=moderate', 2: '&filter=strict'}
  95. '''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
  96. .. code:: yaml
  97. safesearch: true
  98. safes_search_map:
  99. 0: '&filter=none'
  100. 1: '&filter=moderate'
  101. 2: '&filter=strict'
  102. '''
  103. def request(query, params):
  104. '''Build request parameters (see :ref:`engine request`).'''
  105. lang = lang_all
  106. if params['language'] != 'all':
  107. lang = params['language'][:2]
  108. time_range = ''
  109. if params.get('time_range'):
  110. time_range_val = time_range_map.get(params.get('time_range'))
  111. time_range = time_range_url.format(time_range_val=time_range_val)
  112. safe_search = ''
  113. if params['safesearch']:
  114. safe_search = safe_search_map[params['safesearch']]
  115. fargs = {
  116. 'query': urlencode({'q': query})[2:],
  117. 'lang': lang,
  118. 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
  119. 'time_range': time_range,
  120. 'safe_search': safe_search,
  121. }
  122. params['url'] = search_url.format(**fargs)
  123. params['soft_max_redirects'] = soft_max_redirects
  124. return params
  125. def response(resp):
  126. '''Scrap *results* from the response (see :ref:`engine results`).'''
  127. results = []
  128. dom = html.fromstring(resp.text)
  129. is_onion = 'onions' in categories
  130. if results_xpath:
  131. for result in eval_xpath_list(dom, results_xpath):
  132. url = extract_url(eval_xpath_list(result, url_xpath, min_len=1), search_url)
  133. title = extract_text(eval_xpath_list(result, title_xpath, min_len=1))
  134. content = extract_text(eval_xpath_list(result, content_xpath))
  135. tmp_result = {'url': url, 'title': title, 'content': content}
  136. # add thumbnail if available
  137. if thumbnail_xpath:
  138. thumbnail_xpath_result = eval_xpath_list(result, thumbnail_xpath)
  139. if len(thumbnail_xpath_result) > 0:
  140. tmp_result['img_src'] = extract_url(thumbnail_xpath_result, search_url)
  141. # add alternative cached url if available
  142. if cached_xpath:
  143. tmp_result['cached_url'] = cached_url + extract_text(eval_xpath_list(result, cached_xpath, min_len=1))
  144. if is_onion:
  145. tmp_result['is_onion'] = True
  146. results.append(tmp_result)
  147. else:
  148. if cached_xpath:
  149. for url, title, content, cached in zip(
  150. (extract_url(x, search_url) for x in eval_xpath_list(dom, url_xpath)),
  151. map(extract_text, eval_xpath_list(dom, title_xpath)),
  152. map(extract_text, eval_xpath_list(dom, content_xpath)),
  153. map(extract_text, eval_xpath_list(dom, cached_xpath)),
  154. ):
  155. results.append(
  156. {
  157. 'url': url,
  158. 'title': title,
  159. 'content': content,
  160. 'cached_url': cached_url + cached,
  161. 'is_onion': is_onion,
  162. }
  163. )
  164. else:
  165. for url, title, content 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. ):
  170. results.append({'url': url, 'title': title, 'content': content, 'is_onion': is_onion})
  171. if suggestion_xpath:
  172. for suggestion in eval_xpath(dom, suggestion_xpath):
  173. results.append({'suggestion': extract_text(suggestion)})
  174. logger.debug("found %s results", len(results))
  175. return results