yahoo.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Yahoo Search (Web)
  3. Languages are supported by mapping the language to a domain. If domain is not
  4. found in :py:obj:`lang2domain` URL ``<lang>.search.yahoo.com`` is used.
  5. """
  6. from urllib.parse import (
  7. unquote,
  8. urlencode,
  9. )
  10. from lxml import html
  11. from searx.utils import (
  12. eval_xpath_getindex,
  13. eval_xpath_list,
  14. extract_text,
  15. html_to_text,
  16. )
  17. from searx.enginelib.traits import EngineTraits
  18. traits: EngineTraits
  19. # about
  20. about = {
  21. "website": 'https://search.yahoo.com/',
  22. "wikidata_id": None,
  23. "official_api_documentation": 'https://developer.yahoo.com/api/',
  24. "use_official_api": False,
  25. "require_api_key": False,
  26. "results": 'HTML',
  27. }
  28. # engine dependent config
  29. categories = ['general', 'web']
  30. paging = True
  31. time_range_support = True
  32. # send_accept_language_header = True
  33. time_range_dict = {
  34. 'day': ('1d', 'd'),
  35. 'week': ('1w', 'w'),
  36. 'month': ('1m', 'm'),
  37. }
  38. lang2domain = {
  39. 'zh_chs': 'hk.search.yahoo.com',
  40. 'zh_cht': 'tw.search.yahoo.com',
  41. 'any': 'search.yahoo.com',
  42. 'en': 'search.yahoo.com',
  43. 'bg': 'search.yahoo.com',
  44. 'cs': 'search.yahoo.com',
  45. 'da': 'search.yahoo.com',
  46. 'el': 'search.yahoo.com',
  47. 'et': 'search.yahoo.com',
  48. 'he': 'search.yahoo.com',
  49. 'hr': 'search.yahoo.com',
  50. 'ja': 'search.yahoo.com',
  51. 'ko': 'search.yahoo.com',
  52. 'sk': 'search.yahoo.com',
  53. 'sl': 'search.yahoo.com',
  54. }
  55. """Map language to domain"""
  56. locale_aliases = {
  57. 'zh': 'zh_Hans',
  58. 'zh-HK': 'zh_Hans',
  59. 'zh-CN': 'zh_Hans', # dead since 2015 / routed to hk.search.yahoo.com
  60. 'zh-TW': 'zh_Hant',
  61. }
  62. def request(query, params):
  63. """build request"""
  64. lang = locale_aliases.get(params['language'], None)
  65. if not lang:
  66. lang = params['language'].split('-')[0]
  67. lang = traits.get_language(lang, traits.all_locale)
  68. offset = (params['pageno'] - 1) * 7 + 1
  69. age, btf = time_range_dict.get(params['time_range'], ('', ''))
  70. args = urlencode(
  71. {
  72. 'p': query,
  73. 'ei': 'UTF-8',
  74. 'fl': 1,
  75. 'vl': 'lang_' + lang,
  76. 'btf': btf,
  77. 'fr2': 'time',
  78. 'age': age,
  79. 'b': offset,
  80. 'xargs': 0,
  81. }
  82. )
  83. domain = lang2domain.get(lang, '%s.search.yahoo.com' % lang)
  84. params['url'] = 'https://%s/search?%s' % (domain, args)
  85. return params
  86. def parse_url(url_string):
  87. """remove yahoo-specific tracking-url"""
  88. endings = ['/RS', '/RK']
  89. endpositions = []
  90. start = url_string.find('http', url_string.find('/RU=') + 1)
  91. for ending in endings:
  92. endpos = url_string.rfind(ending)
  93. if endpos > -1:
  94. endpositions.append(endpos)
  95. if start == 0 or len(endpositions) == 0:
  96. return url_string
  97. end = min(endpositions)
  98. return unquote(url_string[start:end])
  99. def response(resp):
  100. """parse response"""
  101. results = []
  102. dom = html.fromstring(resp.text)
  103. # parse results
  104. for result in eval_xpath_list(dom, '//div[contains(@class,"algo-sr")]'):
  105. url = eval_xpath_getindex(result, './/h3/a/@href', 0, default=None)
  106. if url is None:
  107. continue
  108. url = parse_url(url)
  109. title = eval_xpath_getindex(result, './/h3//a/@aria-label', 0, default='')
  110. title: str = extract_text(title)
  111. content = eval_xpath_getindex(result, './/div[contains(@class, "compText")]', 0, default='')
  112. content: str = extract_text(content, allow_none=True)
  113. # append result
  114. results.append(
  115. {
  116. 'url': url,
  117. # title sometimes contains HTML tags / see
  118. # https://github.com/searxng/searxng/issues/3790
  119. 'title': " ".join(html_to_text(title).strip().split()),
  120. 'content': " ".join(html_to_text(content).strip().split()),
  121. }
  122. )
  123. for suggestion in eval_xpath_list(dom, '//div[contains(@class, "AlsoTry")]//table//a'):
  124. # append suggestion
  125. results.append({'suggestion': extract_text(suggestion)})
  126. return results
  127. def fetch_traits(engine_traits: EngineTraits):
  128. """Fetch languages from yahoo"""
  129. # pylint: disable=import-outside-toplevel
  130. import babel
  131. from searx import network
  132. from searx.locales import language_tag
  133. engine_traits.all_locale = 'any'
  134. resp = network.get('https://search.yahoo.com/preferences/languages')
  135. if not resp.ok:
  136. print("ERROR: response from yahoo is not OK.")
  137. dom = html.fromstring(resp.text)
  138. offset = len('lang_')
  139. eng2sxng = {'zh_chs': 'zh_Hans', 'zh_cht': 'zh_Hant'}
  140. for val in eval_xpath_list(dom, '//div[contains(@class, "lang-item")]/input/@value'):
  141. eng_tag = val[offset:]
  142. try:
  143. sxng_tag = language_tag(babel.Locale.parse(eng2sxng.get(eng_tag, eng_tag)))
  144. except babel.UnknownLocaleError:
  145. print('ERROR: unknown language --> %s' % eng_tag)
  146. continue
  147. conflict = engine_traits.languages.get(sxng_tag)
  148. if conflict:
  149. if conflict != eng_tag:
  150. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  151. continue
  152. engine_traits.languages[sxng_tag] = eng_tag