sjp.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. }
  18. categories = ['general']
  19. paging = False
  20. URL = 'https://sjp.pwn.pl'
  21. SEARCH_URL = URL + '/szukaj/{query}.html'
  22. word_xpath = '//div[@class="query"]'
  23. dict_xpath = ['//div[@class="wyniki sjp-so-wyniki sjp-so-anchor"]',
  24. '//div[@class="wyniki sjp-wyniki sjp-anchor"]',
  25. '//div[@class="wyniki sjp-doroszewski-wyniki sjp-doroszewski-anchor"]']
  26. def request(query, params):
  27. params['url'] = SEARCH_URL.format(query=query)
  28. logger.debug(f"query_url --> {params['url']}")
  29. return params
  30. def response(resp):
  31. results = []
  32. raise_for_httperror(resp)
  33. dom = fromstring(resp.text)
  34. word = extract_text(dom.xpath(word_xpath))
  35. definitions = []
  36. for dict_src in dict_xpath:
  37. for src in dom.xpath(dict_src):
  38. src_text = extract_text(src.xpath('.//span[@class="entry-head-title"]/text()')).strip()
  39. src_defs = []
  40. for def_item in src.xpath('.//div[contains(@class, "ribbon-element")]'):
  41. if def_item.xpath('./div[@class="znacz"]'):
  42. sub_defs = []
  43. for def_sub_item in def_item.xpath('./div[@class="znacz"]'):
  44. def_sub_text = extract_text(def_sub_item).lstrip('0123456789. ')
  45. sub_defs.append(def_sub_text)
  46. src_defs.append((word, sub_defs))
  47. else:
  48. def_text = extract_text(def_item).strip()
  49. def_link = def_item.xpath('./span/a/@href')
  50. if 'doroszewski' in def_link[0]:
  51. def_text = f"<a href='{def_link[0]}'>{def_text}</a>"
  52. src_defs.append((def_text, ''))
  53. definitions.append((src_text, src_defs))
  54. if not definitions:
  55. return results
  56. infobox = ''
  57. for src in definitions:
  58. infobox += f"<div><small>{src[0]}</small>"
  59. infobox += "<ul>"
  60. for (def_text, sub_def) in src[1]:
  61. infobox += f"<li>{def_text}</li>"
  62. if sub_def:
  63. infobox += "<ol>"
  64. for sub_def_text in sub_def:
  65. infobox += f"<li>{sub_def_text}</li>"
  66. infobox += "</ol>"
  67. infobox += "</ul></div>"
  68. results.append({
  69. 'infobox': word,
  70. 'content': infobox,
  71. })
  72. return results