duden.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Duden
  4. """
  5. import re
  6. from urllib.parse import quote, urljoin
  7. from lxml import html
  8. from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
  9. # about
  10. about = {
  11. "website": 'https://www.duden.de',
  12. "wikidata_id": 'Q73624591',
  13. "official_api_documentation": None,
  14. "use_official_api": False,
  15. "require_api_key": False,
  16. "results": 'HTML',
  17. }
  18. categories = ['general']
  19. paging = True
  20. # search-url
  21. base_url = 'https://www.duden.de/'
  22. search_url = base_url + 'suchen/dudenonline/{query}?search_api_fulltext=&page={offset}'
  23. def request(query, params):
  24. '''pre-request callback
  25. params<dict>:
  26. method : POST/GET
  27. headers : {}
  28. data : {} # if method == POST
  29. url : ''
  30. category: 'search category'
  31. pageno : 1 # number of the requested page
  32. '''
  33. offset = (params['pageno'] - 1)
  34. if offset == 0:
  35. search_url_fmt = base_url + 'suchen/dudenonline/{query}'
  36. params['url'] = search_url_fmt.format(query=quote(query))
  37. else:
  38. params['url'] = search_url.format(offset=offset, query=quote(query))
  39. # after the last page of results, spelling corrections are returned after a HTTP redirect
  40. # whatever the page number is
  41. params['soft_max_redirects'] = 1
  42. return params
  43. def response(resp):
  44. '''post-response callback
  45. resp: requests response object
  46. '''
  47. results = []
  48. dom = html.fromstring(resp.text)
  49. number_of_results_element =\
  50. eval_xpath_getindex(dom, '//a[@class="active" and contains(@href,"/suchen/dudenonline")]/span/text()',
  51. 0, default=None)
  52. if number_of_results_element is not None:
  53. number_of_results_string = re.sub('[^0-9]', '', number_of_results_element)
  54. results.append({'number_of_results': int(number_of_results_string)})
  55. for result in eval_xpath_list(dom, '//section[not(contains(@class, "essay"))]'):
  56. url = eval_xpath_getindex(result, './/h2/a', 0).get('href')
  57. url = urljoin(base_url, url)
  58. title = eval_xpath(result, 'string(.//h2/a)').strip()
  59. content = extract_text(eval_xpath(result, './/p'))
  60. # append result
  61. results.append({'url': url,
  62. 'title': title,
  63. 'content': content})
  64. return results