yahoo.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. Yahoo (Web)
  4. """
  5. from urllib.parse import unquote, urlencode
  6. from lxml import html
  7. from searx.utils import extract_text, extract_url, match_language, eval_xpath
  8. # about
  9. about = {
  10. "website": 'https://search.yahoo.com/',
  11. "wikidata_id": None,
  12. "official_api_documentation": 'https://developer.yahoo.com/api/',
  13. "use_official_api": False,
  14. "require_api_key": False,
  15. "results": 'HTML',
  16. }
  17. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. time_range_support = True
  21. # search-url
  22. base_url = 'https://search.yahoo.com/'
  23. search_url = 'search?{query}&b={offset}&fl=1&vl=lang_{lang}'
  24. search_url_with_time = 'search?{query}&b={offset}&fl=1&vl=lang_{lang}&age={age}&btf={btf}&fr2=time'
  25. supported_languages_url = 'https://search.yahoo.com/web/advanced'
  26. # specific xpath variables
  27. results_xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' Sr ')]"
  28. url_xpath = './/h3/a/@href'
  29. title_xpath = './/h3/a'
  30. content_xpath = './/div[contains(@class, "compText")]'
  31. suggestion_xpath = "//div[contains(concat(' ', normalize-space(@class), ' '), ' AlsoTry ')]//a"
  32. time_range_dict = {'day': ['1d', 'd'],
  33. 'week': ['1w', 'w'],
  34. 'month': ['1m', 'm']}
  35. language_aliases = {'zh-CN': 'zh-CHS', 'zh-TW': 'zh-CHT', 'zh-HK': 'zh-CHT'}
  36. # remove yahoo-specific tracking-url
  37. def parse_url(url_string):
  38. endings = ['/RS', '/RK']
  39. endpositions = []
  40. start = url_string.find('http', url_string.find('/RU=') + 1)
  41. for ending in endings:
  42. endpos = url_string.rfind(ending)
  43. if endpos > -1:
  44. endpositions.append(endpos)
  45. if start == 0 or len(endpositions) == 0:
  46. return url_string
  47. else:
  48. end = min(endpositions)
  49. return unquote(url_string[start:end])
  50. def _get_url(query, offset, language, time_range):
  51. if time_range in time_range_dict:
  52. return base_url + search_url_with_time.format(offset=offset,
  53. query=urlencode({'p': query}),
  54. lang=language,
  55. age=time_range_dict[time_range][0],
  56. btf=time_range_dict[time_range][1])
  57. return base_url + search_url.format(offset=offset,
  58. query=urlencode({'p': query}),
  59. lang=language)
  60. def _get_language(params):
  61. if params['language'] == 'all':
  62. return 'en'
  63. language = match_language(params['language'], supported_languages, language_aliases)
  64. if language not in language_aliases.values():
  65. language = language.split('-')[0]
  66. language = language.replace('-', '_').lower()
  67. return language
  68. # do search-request
  69. def request(query, params):
  70. if params['time_range'] and params['time_range'] not in time_range_dict:
  71. return params
  72. offset = (params['pageno'] - 1) * 10 + 1
  73. language = _get_language(params)
  74. params['url'] = _get_url(query, offset, language, params['time_range'])
  75. # TODO required?
  76. params['cookies']['sB'] = 'fl=1&vl=lang_{lang}&sh=1&rw=new&v=1'\
  77. .format(lang=language)
  78. return params
  79. # get response from search-request
  80. def response(resp):
  81. results = []
  82. dom = html.fromstring(resp.text)
  83. try:
  84. results_num = int(eval_xpath(dom, '//div[@class="compPagination"]/span[last()]/text()')[0]
  85. .split()[0].replace(',', ''))
  86. results.append({'number_of_results': results_num})
  87. except:
  88. pass
  89. # parse results
  90. for result in eval_xpath(dom, results_xpath):
  91. try:
  92. url = parse_url(extract_url(eval_xpath(result, url_xpath), search_url))
  93. title = extract_text(eval_xpath(result, title_xpath)[0])
  94. except:
  95. continue
  96. content = extract_text(eval_xpath(result, content_xpath)[0])
  97. # append result
  98. results.append({'url': url,
  99. 'title': title,
  100. 'content': content})
  101. # if no suggestion found, return results
  102. suggestions = eval_xpath(dom, suggestion_xpath)
  103. if not suggestions:
  104. return results
  105. # parse suggestion
  106. for suggestion in suggestions:
  107. # append suggestion
  108. results.append({'suggestion': extract_text(suggestion)})
  109. # return results
  110. return results
  111. # get supported languages from their site
  112. def _fetch_supported_languages(resp):
  113. supported_languages = []
  114. dom = html.fromstring(resp.text)
  115. options = eval_xpath(dom, '//div[@id="yschlang"]/span/label/input')
  116. for option in options:
  117. code_parts = eval_xpath(option, './@value')[0][5:].split('_')
  118. if len(code_parts) == 2:
  119. code = code_parts[0] + '-' + code_parts[1].upper()
  120. else:
  121. code = code_parts[0]
  122. supported_languages.append(code)
  123. return supported_languages