xpath.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. from lxml import html
  2. from lxml.etree import _ElementStringResult, _ElementUnicodeResult
  3. from searx.utils import html_to_text
  4. from searx.url_utils import unquote, urlencode, urljoin, urlparse
  5. search_url = None
  6. url_xpath = None
  7. content_xpath = None
  8. title_xpath = None
  9. thumbnail_xpath = False
  10. paging = False
  11. suggestion_xpath = ''
  12. results_xpath = ''
  13. # parameters for engines with paging support
  14. #
  15. # number of results on each page
  16. # (only needed if the site requires not a page number, but an offset)
  17. page_size = 1
  18. # number of the first page (usually 0 or 1)
  19. first_page_num = 1
  20. '''
  21. if xpath_results is list, extract the text from each result and concat the list
  22. if xpath_results is a xml element, extract all the text node from it
  23. ( text_content() method from lxml )
  24. if xpath_results is a string element, then it's already done
  25. '''
  26. def extract_text(xpath_results):
  27. if type(xpath_results) == list:
  28. # it's list of result : concat everything using recursive call
  29. result = ''
  30. for e in xpath_results:
  31. result = result + extract_text(e)
  32. return result.strip()
  33. elif type(xpath_results) in [_ElementStringResult, _ElementUnicodeResult]:
  34. # it's a string
  35. return ''.join(xpath_results)
  36. else:
  37. # it's a element
  38. text = html.tostring(
  39. xpath_results, encoding='unicode', method='text', with_tail=False
  40. )
  41. text = text.strip().replace('\n', ' ')
  42. return ' '.join(text.split())
  43. def extract_url(xpath_results, search_url):
  44. if xpath_results == []:
  45. raise Exception('Empty url resultset')
  46. url = extract_text(xpath_results)
  47. if url.startswith('//'):
  48. # add http or https to this kind of url //example.com/
  49. parsed_search_url = urlparse(search_url)
  50. url = u'{0}:{1}'.format(parsed_search_url.scheme or 'http', url)
  51. elif url.startswith('/'):
  52. # fix relative url to the search engine
  53. url = urljoin(search_url, url)
  54. # normalize url
  55. url = normalize_url(url)
  56. return url
  57. def normalize_url(url):
  58. parsed_url = urlparse(url)
  59. # add a / at this end of the url if there is no path
  60. if not parsed_url.netloc:
  61. raise Exception('Cannot parse url')
  62. if not parsed_url.path:
  63. url += '/'
  64. # FIXME : hack for yahoo
  65. if parsed_url.hostname == 'search.yahoo.com'\
  66. and parsed_url.path.startswith('/r'):
  67. p = parsed_url.path
  68. mark = p.find('/**')
  69. if mark != -1:
  70. return unquote(p[mark + 3:]).decode('utf-8')
  71. return url
  72. def request(query, params):
  73. query = urlencode({'q': query})[2:]
  74. fp = {'query': query}
  75. if paging and search_url.find('{pageno}') >= 0:
  76. fp['pageno'] = (params['pageno'] - 1) * page_size + first_page_num
  77. params['url'] = search_url.format(**fp)
  78. params['query'] = query
  79. return params
  80. def response(resp):
  81. results = []
  82. dom = html.fromstring(resp.text)
  83. if results_xpath:
  84. for result in dom.xpath(results_xpath):
  85. url = extract_url(result.xpath(url_xpath), search_url)
  86. title = extract_text(result.xpath(title_xpath))
  87. content = extract_text(result.xpath(content_xpath))
  88. tmp_result = {'url': url, 'title': title, 'content': content}
  89. # add thumbnail if available
  90. if thumbnail_xpath:
  91. thumbnail_xpath_result = result.xpath(thumbnail_xpath)
  92. if len(thumbnail_xpath_result) > 0:
  93. tmp_result['img_src'] = extract_url(thumbnail_xpath_result, search_url)
  94. results.append(tmp_result)
  95. else:
  96. for url, title, content in zip(
  97. (extract_url(x, search_url) for
  98. x in dom.xpath(url_xpath)),
  99. map(extract_text, dom.xpath(title_xpath)),
  100. map(extract_text, dom.xpath(content_xpath))
  101. ):
  102. results.append({'url': url, 'title': title, 'content': content})
  103. if not suggestion_xpath:
  104. return results
  105. for suggestion in dom.xpath(suggestion_xpath):
  106. results.append({'suggestion': extract_text(suggestion)})
  107. return results