xpath.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from lxml import html
  2. from urllib.parse import urlencode
  3. from searx.utils import extract_text, extract_url, eval_xpath
  4. search_url = None
  5. url_xpath = None
  6. content_xpath = None
  7. title_xpath = None
  8. thumbnail_xpath = False
  9. paging = False
  10. suggestion_xpath = ''
  11. results_xpath = ''
  12. # parameters for engines with paging support
  13. #
  14. # number of results on each page
  15. # (only needed if the site requires not a page number, but an offset)
  16. page_size = 1
  17. # number of the first page (usually 0 or 1)
  18. first_page_num = 1
  19. def request(query, params):
  20. query = urlencode({'q': query})[2:]
  21. fp = {'query': query}
  22. if paging and search_url.find('{pageno}') >= 0:
  23. fp['pageno'] = (params['pageno'] - 1) * page_size + first_page_num
  24. params['url'] = search_url.format(**fp)
  25. params['query'] = query
  26. return params
  27. def response(resp):
  28. results = []
  29. dom = html.fromstring(resp.text)
  30. if results_xpath:
  31. for result in eval_xpath(dom, results_xpath):
  32. url = extract_url(eval_xpath(result, url_xpath), search_url)
  33. title = extract_text(eval_xpath(result, title_xpath))
  34. content = extract_text(eval_xpath(result, content_xpath))
  35. tmp_result = {'url': url, 'title': title, 'content': content}
  36. # add thumbnail if available
  37. if thumbnail_xpath:
  38. thumbnail_xpath_result = eval_xpath(result, thumbnail_xpath)
  39. if len(thumbnail_xpath_result) > 0:
  40. tmp_result['img_src'] = extract_url(thumbnail_xpath_result, search_url)
  41. results.append(tmp_result)
  42. else:
  43. for url, title, content in zip(
  44. (extract_url(x, search_url) for
  45. x in eval_xpath(dom, url_xpath)),
  46. map(extract_text, eval_xpath(dom, title_xpath)),
  47. map(extract_text, eval_xpath(dom, content_xpath))
  48. ):
  49. results.append({'url': url, 'title': title, 'content': content})
  50. if not suggestion_xpath:
  51. return results
  52. for suggestion in eval_xpath(dom, suggestion_xpath):
  53. results.append({'suggestion': extract_text(suggestion)})
  54. return results