xpath.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. from searx import logger
  21. logger = logger.getChild('XPath engine')
  22. search_url = None
  23. """
  24. Search URL of the engine, replacements are:
  25. ``{query}``:
  26. Search terms from user.
  27. ``{pageno}``:
  28. Page number if engine supports pagging :py:obj:`paging`
  29. """
  30. soft_max_redirects = 0
  31. '''Maximum redirects, soft limit. Record an error but don't stop the engine'''
  32. results_xpath = ''
  33. '''XPath selector for the list of result items'''
  34. url_xpath = None
  35. '''XPath selector of result's ``url``.'''
  36. content_xpath = None
  37. '''XPath selector of result's ``content``.'''
  38. title_xpath = None
  39. '''XPath selector of result's ``title``.'''
  40. thumbnail_xpath = False
  41. '''XPath selector of result's ``img_src``.'''
  42. suggestion_xpath = ''
  43. '''XPath selector of result's ``suggestion``.'''
  44. cached_xpath = ''
  45. cached_url = ''
  46. paging = False
  47. '''Engine supports paging [True or False].'''
  48. page_size = 1
  49. '''Number of results on each page. Only needed if the site requires not a page
  50. number, but an offset.'''
  51. first_page_num = 1
  52. '''Number of the first page (usually 0 or 1).'''
  53. def request(query, params):
  54. '''Build request parameters (see :ref:`engine request`).
  55. '''
  56. query = urlencode({'q': query})[2:]
  57. fargs = {'query': query}
  58. if paging and search_url.find('{pageno}') >= 0:
  59. fargs['pageno'] = (params['pageno'] - 1) * page_size + first_page_num
  60. params['url'] = search_url.format(**fargs)
  61. params['query'] = query
  62. params['soft_max_redirects'] = soft_max_redirects
  63. logger.debug("query_url --> %s", params['url'])
  64. return params
  65. def response(resp):
  66. '''Scrap *results* from the response (see :ref:`engine results`).
  67. '''
  68. results = []
  69. dom = html.fromstring(resp.text)
  70. is_onion = 'onions' in categories # pylint: disable=undefined-variable
  71. if results_xpath:
  72. for result in eval_xpath_list(dom, results_xpath):
  73. url = extract_url(eval_xpath_list(result, url_xpath, min_len=1), search_url)
  74. title = extract_text(eval_xpath_list(result, title_xpath, min_len=1))
  75. content = extract_text(eval_xpath_list(result, content_xpath, min_len=1))
  76. tmp_result = {'url': url, 'title': title, 'content': content}
  77. # add thumbnail if available
  78. if thumbnail_xpath:
  79. thumbnail_xpath_result = eval_xpath_list(result, thumbnail_xpath)
  80. if len(thumbnail_xpath_result) > 0:
  81. tmp_result['img_src'] = extract_url(thumbnail_xpath_result, search_url)
  82. # add alternative cached url if available
  83. if cached_xpath:
  84. tmp_result['cached_url'] = (
  85. cached_url
  86. + extract_text(eval_xpath_list(result, cached_xpath, min_len=1))
  87. )
  88. if is_onion:
  89. tmp_result['is_onion'] = True
  90. results.append(tmp_result)
  91. else:
  92. if cached_xpath:
  93. for url, title, content, cached in zip(
  94. (extract_url(x, search_url) for
  95. x in eval_xpath_list(dom, url_xpath)),
  96. map(extract_text, eval_xpath_list(dom, title_xpath)),
  97. map(extract_text, eval_xpath_list(dom, content_xpath)),
  98. map(extract_text, eval_xpath_list(dom, cached_xpath))
  99. ):
  100. results.append({
  101. 'url': url,
  102. 'title': title,
  103. 'content': content,
  104. 'cached_url': cached_url + cached, 'is_onion': is_onion
  105. })
  106. else:
  107. for url, title, content in zip(
  108. (extract_url(x, search_url) for
  109. x in eval_xpath_list(dom, url_xpath)),
  110. map(extract_text, eval_xpath_list(dom, title_xpath)),
  111. map(extract_text, eval_xpath_list(dom, content_xpath))
  112. ):
  113. results.append({
  114. 'url': url,
  115. 'title': title,
  116. 'content': content,
  117. 'is_onion': is_onion
  118. })
  119. if suggestion_xpath:
  120. for suggestion in eval_xpath(dom, suggestion_xpath):
  121. results.append({'suggestion': extract_text(suggestion)})
  122. logger.debug("found %s results", len(results))
  123. return results