stackoverflow.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. Stackoverflow (It)
  3. @website https://stackoverflow.com/
  4. @provide-api not clear (https://api.stackexchange.com/docs/advanced-search)
  5. @using-api no
  6. @results HTML
  7. @stable no (HTML can change)
  8. @parse url, title, content
  9. """
  10. from urlparse import urljoin
  11. from urllib import urlencode
  12. from lxml import html
  13. from searx.engines.xpath import extract_text
  14. # engine dependent config
  15. categories = ['it']
  16. paging = True
  17. # search-url
  18. url = 'https://stackoverflow.com/'
  19. search_url = url + 'search?{query}&page={pageno}'
  20. # specific xpath variables
  21. results_xpath = '//div[contains(@class,"question-summary")]'
  22. link_xpath = './/div[@class="result-link"]//a|.//div[@class="summary"]//h3//a'
  23. content_xpath = './/div[@class="excerpt"]'
  24. # do search-request
  25. def request(query, params):
  26. params['url'] = search_url.format(query=urlencode({'q': query}),
  27. pageno=params['pageno'])
  28. return params
  29. # get response from search-request
  30. def response(resp):
  31. results = []
  32. dom = html.fromstring(resp.text)
  33. # parse results
  34. for result in dom.xpath(results_xpath):
  35. link = result.xpath(link_xpath)[0]
  36. href = urljoin(url, link.attrib.get('href'))
  37. title = extract_text(link)
  38. content = extract_text(result.xpath(content_xpath))
  39. # append result
  40. results.append({'url': href,
  41. 'title': title,
  42. 'content': content})
  43. # return results
  44. return results