yahoo.py 2.7 KB

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