sjp.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Słownik Języka Polskiego (general)
  3. """
  4. from lxml.html import fromstring
  5. from searx import logger
  6. from searx.utils import extract_text
  7. from searx.network import raise_for_httperror
  8. logger = logger.getChild('sjp engine')
  9. # about
  10. about = {
  11. "website": 'https://sjp.pwn.pl',
  12. "wikidata_id": 'Q55117369',
  13. "official_api_documentation": None,
  14. "use_official_api": False,
  15. "require_api_key": False,
  16. "results": 'HTML',
  17. "language": 'pl',
  18. }
  19. categories = ['general']
  20. paging = False
  21. URL = 'https://sjp.pwn.pl'
  22. SEARCH_URL = URL + '/szukaj/{query}.html'
  23. word_xpath = '//div[@class="query"]'
  24. dict_xpath = ['//div[@class="wyniki sjp-so-wyniki sjp-so-anchor"]',
  25. '//div[@class="wyniki sjp-wyniki sjp-anchor"]',
  26. '//div[@class="wyniki sjp-doroszewski-wyniki sjp-doroszewski-anchor"]']
  27. def request(query, params):
  28. params['url'] = SEARCH_URL.format(query=query)
  29. logger.debug(f"query_url --> {params['url']}")
  30. return params
  31. def response(resp):
  32. results = []
  33. raise_for_httperror(resp)
  34. dom = fromstring(resp.text)
  35. word = extract_text(dom.xpath(word_xpath))
  36. definitions = []
  37. for dict_src in dict_xpath:
  38. for src in dom.xpath(dict_src):
  39. src_text = extract_text(src.xpath('.//span[@class="entry-head-title"]/text()')).strip()
  40. src_defs = []
  41. for def_item in src.xpath('.//div[contains(@class, "ribbon-element")]'):
  42. if def_item.xpath('./div[@class="znacz"]'):
  43. sub_defs = []
  44. for def_sub_item in def_item.xpath('./div[@class="znacz"]'):
  45. def_sub_text = extract_text(def_sub_item).lstrip('0123456789. ')
  46. sub_defs.append(def_sub_text)
  47. src_defs.append((word, sub_defs))
  48. else:
  49. def_text = extract_text(def_item).strip()
  50. def_link = def_item.xpath('./span/a/@href')
  51. if 'doroszewski' in def_link[0]:
  52. def_text = f"<a href='{def_link[0]}'>{def_text}</a>"
  53. src_defs.append((def_text, ''))
  54. definitions.append((src_text, src_defs))
  55. if not definitions:
  56. return results
  57. infobox = ''
  58. for src in definitions:
  59. infobox += f"<div><small>{src[0]}</small>"
  60. infobox += "<ul>"
  61. for (def_text, sub_def) in src[1]:
  62. infobox += f"<li>{def_text}</li>"
  63. if sub_def:
  64. infobox += "<ol>"
  65. for sub_def_text in sub_def:
  66. infobox += f"<li>{sub_def_text}</li>"
  67. infobox += "</ol>"
  68. infobox += "</ul></div>"
  69. results.append({
  70. 'infobox': word,
  71. 'content': infobox,
  72. })
  73. return results