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