duden.py 2.4 KB

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