yahoo.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. ## Yahoo (Web)
  2. #
  3. # @website https://search.yahoo.com/web
  4. # @provide-api yes (https://developer.yahoo.com/boss/search/), $0.80/1000 queries
  5. #
  6. # @using-api no (because pricing)
  7. # @results HTML (using search portal)
  8. # @stable no (HTML can change)
  9. # @parse url, title, content, suggestion
  10. from urllib import urlencode
  11. from urlparse import unquote
  12. from lxml import html
  13. from searx.engines.xpath import extract_text, extract_url
  14. # engine dependent config
  15. categories = ['general']
  16. paging = True
  17. language_support = True
  18. # search-url
  19. search_url = 'https://search.yahoo.com/search?{query}&b={offset}&fl=1&vl=lang_{lang}'
  20. # specific xpath variables
  21. results_xpath = '//div[@class="res"]'
  22. url_xpath = './/h3/a/@href'
  23. title_xpath = './/h3/a'
  24. content_xpath = './/div[@class="abstr"]'
  25. suggestion_xpath = '//div[@id="satat"]//a'
  26. # remove yahoo-specific tracking-url
  27. def parse_url(url_string):
  28. endings = ['/RS', '/RK']
  29. endpositions = []
  30. start = url_string.find('http', url_string.find('/RU=')+1)
  31. for ending in endings:
  32. endpos = url_string.rfind(ending)
  33. if endpos > -1:
  34. endpositions.append(endpos)
  35. end = min(endpositions)
  36. return unquote(url_string[start:end])
  37. # do search-request
  38. def request(query, params):
  39. offset = (params['pageno'] - 1) * 10 + 1
  40. if params['language'] == 'all':
  41. language = 'en'
  42. else:
  43. language = params['language'].split('_')[0]
  44. params['url'] = search_url.format(offset=offset,
  45. query=urlencode({'p': query}),
  46. lang=language)
  47. # TODO required?
  48. params['cookies']['sB'] = 'fl=1&vl=lang_{lang}&sh=1&rw=new&v=1'\
  49. .format(lang=language)
  50. return params
  51. # get response from search-request
  52. def response(resp):
  53. results = []
  54. dom = html.fromstring(resp.text)
  55. # parse results
  56. for result in dom.xpath(results_xpath):
  57. try:
  58. url = parse_url(extract_url(result.xpath(url_xpath), search_url))
  59. title = extract_text(result.xpath(title_xpath)[0])
  60. except:
  61. continue
  62. content = extract_text(result.xpath(content_xpath)[0])
  63. # append result
  64. results.append({'url': url,
  65. 'title': title,
  66. 'content': content})
  67. # if no suggestion found, return results
  68. if not suggestion_xpath:
  69. return results
  70. # parse suggestion
  71. for suggestion in dom.xpath(suggestion_xpath):
  72. # append suggestion
  73. results.append({'suggestion': extract_text(suggestion)})
  74. # return results
  75. return results