xpath.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 = {
  95. 0: '&filter=none',
  96. 1: '&filter=moderate',
  97. 2: '&filter=strict'
  98. }
  99. '''Maps safe-search value to ``{safe_search}`` in :py:obj:`search_url`.
  100. .. code:: yaml
  101. safesearch: true
  102. safes_search_map:
  103. 0: '&filter=none'
  104. 1: '&filter=moderate'
  105. 2: '&filter=strict'
  106. '''
  107. def request(query, params):
  108. '''Build request parameters (see :ref:`engine request`).
  109. '''
  110. lang = lang_all
  111. if params['language'] != 'all':
  112. lang = params['language'][:2]
  113. time_range = ''
  114. if params.get('time_range'):
  115. time_range_val = time_range_map.get(params.get('time_range'))
  116. time_range = time_range_url.format(time_range_val=time_range_val)
  117. safe_search = ''
  118. if params['safesearch']:
  119. safe_search = safe_search_map[params['safesearch']]
  120. fargs = {
  121. 'query': urlencode({'q': query})[2:],
  122. 'lang': lang,
  123. 'pageno': (params['pageno'] - 1) * page_size + first_page_num,
  124. 'time_range' : time_range,
  125. 'safe_search' : safe_search,
  126. }
  127. params['url'] = search_url.format(**fargs)
  128. params['soft_max_redirects'] = soft_max_redirects
  129. logger.debug("query_url --> %s", params['url'])
  130. return params
  131. def response(resp):
  132. '''Scrap *results* from the response (see :ref:`engine results`).
  133. '''
  134. results = []
  135. dom = html.fromstring(resp.text)
  136. is_onion = 'onions' in categories
  137. if results_xpath:
  138. for result in eval_xpath_list(dom, results_xpath):
  139. url = extract_url(eval_xpath_list(result, url_xpath, min_len=1), search_url)
  140. title = extract_text(eval_xpath_list(result, title_xpath, min_len=1))
  141. content = extract_text(eval_xpath_list(result, content_xpath))
  142. tmp_result = {'url': url, 'title': title, 'content': content}
  143. # add thumbnail if available
  144. if thumbnail_xpath:
  145. thumbnail_xpath_result = eval_xpath_list(result, thumbnail_xpath)
  146. if len(thumbnail_xpath_result) > 0:
  147. tmp_result['img_src'] = extract_url(thumbnail_xpath_result, search_url)
  148. # add alternative cached url if available
  149. if cached_xpath:
  150. tmp_result['cached_url'] = (
  151. cached_url
  152. + extract_text(eval_xpath_list(result, cached_xpath, min_len=1))
  153. )
  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
  161. x in eval_xpath_list(dom, url_xpath)),
  162. map(extract_text, eval_xpath_list(dom, title_xpath)),
  163. map(extract_text, eval_xpath_list(dom, content_xpath)),
  164. map(extract_text, eval_xpath_list(dom, cached_xpath))
  165. ):
  166. results.append({
  167. 'url': url,
  168. 'title': title,
  169. 'content': content,
  170. 'cached_url': cached_url + cached, 'is_onion': is_onion
  171. })
  172. else:
  173. for url, title, content in zip(
  174. (extract_url(x, search_url) for
  175. x in eval_xpath_list(dom, url_xpath)),
  176. map(extract_text, eval_xpath_list(dom, title_xpath)),
  177. map(extract_text, eval_xpath_list(dom, content_xpath))
  178. ):
  179. results.append({
  180. 'url': url,
  181. 'title': title,
  182. 'content': content,
  183. 'is_onion': is_onion
  184. })
  185. if suggestion_xpath:
  186. for suggestion in eval_xpath(dom, suggestion_xpath):
  187. results.append({'suggestion': extract_text(suggestion)})
  188. logger.debug("found %s results", len(results))
  189. return results