.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
google.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""This is the implementation of the Google WEB engine. Some of this
3implementations (manly the :py:obj:`get_google_info`) are shared by other
4engines:
5
6- :ref:`google images engine`
7- :ref:`google news engine`
8- :ref:`google videos engine`
9- :ref:`google scholar engine`
10- :ref:`google autocomplete`
11
12"""
13
14from typing import TYPE_CHECKING
15
16import re
17from urllib.parse import urlencode
18from lxml import html
19import babel
20import babel.core
21import babel.languages
22
23from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
24from searx.locales import language_tag, region_tag, get_official_locales
25from searx.network import get # see https://github.com/searxng/searxng/issues/762
26from searx.exceptions import SearxEngineCaptchaException
27from searx.enginelib.traits import EngineTraits
28
29if TYPE_CHECKING:
30 import logging
31
32 logger: logging.Logger
33
34traits: EngineTraits
35
36
37# about
38about = {
39 "website": 'https://www.google.com',
40 "wikidata_id": 'Q9366',
41 "official_api_documentation": 'https://developers.google.com/custom-search/',
42 "use_official_api": False,
43 "require_api_key": False,
44 "results": 'HTML',
45}
46
47# engine dependent config
48categories = ['general', 'web']
49paging = True
50max_page = 50
51time_range_support = True
52safesearch = True
53
54time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
55
56# Filter results. 0: None, 1: Moderate, 2: Strict
57filter_mapping = {0: 'off', 1: 'medium', 2: 'high'}
58
59# specific xpath variables
60# ------------------------
61
62results_xpath = './/div[contains(@jscontroller, "SC7lYd")]'
63title_xpath = './/a/h3[1]'
64href_xpath = './/a[h3]/@href'
65content_xpath = './/div[contains(@data-sncf, "1")]'
66
67# Suggestions are links placed in a *card-section*, we extract only the text
68# from the links not the links itself.
69suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'
70
71# UI_ASYNC = 'use_ac:true,_fmt:html' # returns a HTTP 500 when user search for
72# # celebrities like '!google natasha allegri'
73# # or '!google chris evans'
74UI_ASYNC = 'use_ac:true,_fmt:prog'
75"""Format of the response from UI's async request."""
76
77
78def get_google_info(params, eng_traits):
79 """Composing various (language) properties for the google engines (:ref:`google
80 API`).
81
82 This function is called by the various google engines (:ref:`google web
83 engine`, :ref:`google images engine`, :ref:`google news engine` and
84 :ref:`google videos engine`).
85
86 :param dict param: Request parameters of the engine. At least
87 a ``searxng_locale`` key should be in the dictionary.
88
89 :param eng_traits: Engine's traits fetched from google preferences
90 (:py:obj:`searx.enginelib.traits.EngineTraits`)
91
92 :rtype: dict
93 :returns:
94 Py-Dictionary with the key/value pairs:
95
96 language:
97 The language code that is used by google (e.g. ``lang_en`` or
98 ``lang_zh-TW``)
99
100 country:
101 The country code that is used by google (e.g. ``US`` or ``TW``)
102
103 locale:
104 A instance of :py:obj:`babel.core.Locale` build from the
105 ``searxng_locale`` value.
106
107 subdomain:
108 Google subdomain :py:obj:`google_domains` that fits to the country
109 code.
110
111 params:
112 Py-Dictionary with additional request arguments (can be passed to
113 :py:func:`urllib.parse.urlencode`).
114
115 - ``hl`` parameter: specifies the interface language of user interface.
116 - ``lr`` parameter: restricts search results to documents written in
117 a particular language.
118 - ``cr`` parameter: restricts search results to documents
119 originating in a particular country.
120 - ``ie`` parameter: sets the character encoding scheme that should
121 be used to interpret the query string ('utf8').
122 - ``oe`` parameter: sets the character encoding scheme that should
123 be used to decode the XML result ('utf8').
124
125 headers:
126 Py-Dictionary with additional HTTP headers (can be passed to
127 request's headers)
128
129 - ``Accept: '*/*``
130
131 """
132
133 ret_val = {
134 'language': None,
135 'country': None,
136 'subdomain': None,
137 'params': {},
138 'headers': {},
139 'cookies': {},
140 'locale': None,
141 }
142
143 sxng_locale = params.get('searxng_locale', 'all')
144 try:
145 locale = babel.Locale.parse(sxng_locale, sep='-')
146 except babel.core.UnknownLocaleError:
147 locale = None
148
149 eng_lang = eng_traits.get_language(sxng_locale, 'lang_en')
150 lang_code = eng_lang.split('_')[-1] # lang_zh-TW --> zh-TW / lang_en --> en
151 country = eng_traits.get_region(sxng_locale, eng_traits.all_locale)
152
153 # Test zh_hans & zh_hant --> in the topmost links in the result list of list
154 # TW and HK you should a find wiktionary.org zh_hant link. In the result
155 # list of zh-CN should not be no hant link instead you should find
156 # zh.m.wikipedia.org/zh somewhere in the top.
157
158 # '!go 日 :zh-TW' --> https://zh.m.wiktionary.org/zh-hant/%E6%97%A5
159 # '!go 日 :zh-CN' --> https://zh.m.wikipedia.org/zh/%E6%97%A5
160
161 ret_val['language'] = eng_lang
162 ret_val['country'] = country
163 ret_val['locale'] = locale
164 ret_val['subdomain'] = eng_traits.custom['supported_domains'].get(country.upper(), 'www.google.com')
165
166 # hl parameter:
167 # The hl parameter specifies the interface language (host language) of
168 # your user interface. To improve the performance and the quality of your
169 # search results, you are strongly encouraged to set this parameter
170 # explicitly.
171 # https://developers.google.com/custom-search/docs/xml_results#hlsp
172 # The Interface Language:
173 # https://developers.google.com/custom-search/docs/xml_results_appendices#interfaceLanguages
174
175 # https://github.com/searxng/searxng/issues/2515#issuecomment-1607150817
176 ret_val['params']['hl'] = f'{lang_code}-{country}'
177
178 # lr parameter:
179 # The lr (language restrict) parameter restricts search results to
180 # documents written in a particular language.
181 # https://developers.google.com/custom-search/docs/xml_results#lrsp
182 # Language Collection Values:
183 # https://developers.google.com/custom-search/docs/xml_results_appendices#languageCollections
184 #
185 # To select 'all' languages an empty 'lr' value is used.
186 #
187 # Different to other google services, Google Scholar supports to select more
188 # than one language. The languages are separated by a pipe '|' (logical OR).
189 # By example: &lr=lang_zh-TW%7Clang_de selects articles written in
190 # traditional chinese OR german language.
191
192 ret_val['params']['lr'] = eng_lang
193 if sxng_locale == 'all':
194 ret_val['params']['lr'] = ''
195
196 # cr parameter:
197 # The cr parameter restricts search results to documents originating in a
198 # particular country.
199 # https://developers.google.com/custom-search/docs/xml_results#crsp
200
201 # specify a region (country) only if a region is given in the selected
202 # locale --> https://github.com/searxng/searxng/issues/2672
203 ret_val['params']['cr'] = ''
204 if len(sxng_locale.split('-')) > 1:
205 ret_val['params']['cr'] = 'country' + country
206
207 # gl parameter: (mandatory by Google News)
208 # The gl parameter value is a two-letter country code. For WebSearch
209 # results, the gl parameter boosts search results whose country of origin
210 # matches the parameter value. See the Country Codes section for a list of
211 # valid values.
212 # Specifying a gl parameter value in WebSearch requests should improve the
213 # relevance of results. This is particularly true for international
214 # customers and, even more specifically, for customers in English-speaking
215 # countries other than the United States.
216 # https://developers.google.com/custom-search/docs/xml_results#glsp
217
218 # https://github.com/searxng/searxng/issues/2515#issuecomment-1606294635
219 # ret_val['params']['gl'] = country
220
221 # ie parameter:
222 # The ie parameter sets the character encoding scheme that should be used
223 # to interpret the query string. The default ie value is latin1.
224 # https://developers.google.com/custom-search/docs/xml_results#iesp
225
226 ret_val['params']['ie'] = 'utf8'
227
228 # oe parameter:
229 # The oe parameter sets the character encoding scheme that should be used
230 # to decode the XML result. The default oe value is latin1.
231 # https://developers.google.com/custom-search/docs/xml_results#oesp
232
233 ret_val['params']['oe'] = 'utf8'
234
235 # num parameter:
236 # The num parameter identifies the number of search results to return.
237 # The default num value is 10, and the maximum value is 20. If you request
238 # more than 20 results, only 20 results will be returned.
239 # https://developers.google.com/custom-search/docs/xml_results#numsp
240
241 # HINT: seems to have no effect (tested in google WEB & Images)
242 # ret_val['params']['num'] = 20
243
244 # HTTP headers
245
246 ret_val['headers']['Accept'] = '*/*'
247
248 # Cookies
249
250 # - https://github.com/searxng/searxng/pull/1679#issuecomment-1235432746
251 # - https://github.com/searxng/searxng/issues/1555
252 ret_val['cookies']['CONSENT'] = "YES+"
253
254 return ret_val
255
256
258 if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
260
261
262def request(query, params):
263 """Google search request"""
264 # pylint: disable=line-too-long
265 offset = (params['pageno'] - 1) * 10
266 google_info = get_google_info(params, traits)
267
268 # https://www.google.de/search?q=corona&hl=de&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
269 query_url = (
270 'https://'
271 + google_info['subdomain']
272 + '/search'
273 + "?"
274 + urlencode(
275 {
276 'q': query,
277 **google_info['params'],
278 'filter': '0',
279 'start': offset,
280 # 'vet': '12ahUKEwik3ZbIzfn7AhXMX_EDHbUDBh0QxK8CegQIARAC..i',
281 # 'ved': '2ahUKEwik3ZbIzfn7AhXMX_EDHbUDBh0Q_skCegQIARAG',
282 # 'cs' : 1,
283 # 'sa': 'N',
284 # 'yv': 3,
285 # 'prmd': 'vin',
286 # 'ei': 'GASaY6TxOcy_xc8PtYeY6AE',
287 # 'sa': 'N',
288 # 'sstk': 'AcOHfVkD7sWCSAheZi-0tx_09XDO55gTWY0JNq3_V26cNN-c8lfD45aZYPI8s_Bqp8s57AHz5pxchDtAGCA_cikAWSjy9kw3kgg'
289 # formally known as use_mobile_ui
290 'asearch': 'arc',
291 'async': UI_ASYNC,
292 }
293 )
294 )
295
296 if params['time_range'] in time_range_dict:
297 query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
298 if params['safesearch']:
299 query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
300 params['url'] = query_url
301
302 params['cookies'] = google_info['cookies']
303 params['headers'].update(google_info['headers'])
304 return params
305
306
307# =26;[3,"dimg_ZNMiZPCqE4apxc8P3a2tuAQ_137"]a87;data:image/jpeg;base64,/9j/4AAQSkZJRgABA
308# ...6T+9Nl4cnD+gr9OK8I56/tX3l86nWYw//2Q==26;
309RE_DATA_IMAGE = re.compile(r'"(dimg_[^"]*)"[^;]*;(data:image[^;]*;[^;]*);')
310
311
313 data_image_map = {}
314 for img_id, data_image in RE_DATA_IMAGE.findall(dom.text_content()):
315 end_pos = data_image.rfind('=')
316 if end_pos > 0:
317 data_image = data_image[: end_pos + 1]
318 data_image_map[img_id] = data_image
319 logger.debug('data:image objects --> %s', list(data_image_map.keys()))
320 return data_image_map
321
322
323def response(resp):
324 """Get response from google's search request"""
325 # pylint: disable=too-many-branches, too-many-statements
326 detect_google_sorry(resp)
327
328 results = []
329
330 # convert the text to dom
331 dom = html.fromstring(resp.text)
332 data_image_map = _parse_data_images(dom)
333
334 # results --> answer
335 answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
336 for item in answer_list:
337 for bubble in eval_xpath(item, './/div[@class="nnFGuf"]'):
338 bubble.drop_tree()
339 results.append(
340 {
341 'answer': extract_text(item),
342 'url': (eval_xpath(item, '../..//a/@href') + [None])[0],
343 }
344 )
345
346 # parse results
347
348 for result in eval_xpath_list(dom, results_xpath): # pylint: disable=too-many-nested-blocks
349
350 try:
351 title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
352 if title_tag is None:
353 # this not one of the common google results *section*
354 logger.debug('ignoring item from the result_xpath list: missing title')
355 continue
356 title = extract_text(title_tag)
357
358 url = eval_xpath_getindex(result, href_xpath, 0, None)
359 if url is None:
360 logger.debug('ignoring item from the result_xpath list: missing url of title "%s"', title)
361 continue
362
363 content_nodes = eval_xpath(result, content_xpath)
364 content = extract_text(content_nodes)
365
366 if not content:
367 logger.debug('ignoring item from the result_xpath list: missing content of title "%s"', title)
368 continue
369
370 thumbnail = content_nodes[0].xpath('.//img/@src')
371 if thumbnail:
372 thumbnail = thumbnail[0]
373 if thumbnail.startswith('data:image'):
374 img_id = content_nodes[0].xpath('.//img/@id')
375 if img_id:
376 thumbnail = data_image_map.get(img_id[0])
377 else:
378 thumbnail = None
379
380 results.append({'url': url, 'title': title, 'content': content, 'thumbnail': thumbnail})
381
382 except Exception as e: # pylint: disable=broad-except
383 logger.error(e, exc_info=True)
384 continue
385
386 # parse suggestion
387 for suggestion in eval_xpath_list(dom, suggestion_xpath):
388 # append suggestion
389 results.append({'suggestion': extract_text(suggestion)})
390
391 # return results
392 return results
393
394
395# get supported languages from their site
396
397
398skip_countries = [
399 # official language of google-country not in google-languages
400 'AL', # Albanien (sq)
401 'AZ', # Aserbaidschan (az)
402 'BD', # Bangladesch (bn)
403 'BN', # Brunei Darussalam (ms)
404 'BT', # Bhutan (dz)
405 'ET', # Äthiopien (am)
406 'GE', # Georgien (ka, os)
407 'GL', # Grönland (kl)
408 'KH', # Kambodscha (km)
409 'LA', # Laos (lo)
410 'LK', # Sri Lanka (si, ta)
411 'ME', # Montenegro (sr)
412 'MK', # Nordmazedonien (mk, sq)
413 'MM', # Myanmar (my)
414 'MN', # Mongolei (mn)
415 'MV', # Malediven (dv) // dv_MV is unknown by babel
416 'MY', # Malaysia (ms)
417 'NP', # Nepal (ne)
418 'TJ', # Tadschikistan (tg)
419 'TM', # Turkmenistan (tk)
420 'UZ', # Usbekistan (uz)
421]
422
423
424def fetch_traits(engine_traits: EngineTraits, add_domains: bool = True):
425 """Fetch languages from Google."""
426 # pylint: disable=import-outside-toplevel, too-many-branches
427
428 engine_traits.custom['supported_domains'] = {}
429
430 resp = get('https://www.google.com/preferences')
431 if not resp.ok: # type: ignore
432 raise RuntimeError("Response from Google's preferences is not OK.")
433
434 dom = html.fromstring(resp.text.replace('<?xml version="1.0" encoding="UTF-8"?>', ''))
435
436 # supported language codes
437
438 lang_map = {'no': 'nb'}
439 for x in eval_xpath_list(dom, "//select[@name='hl']/option"):
440 eng_lang = x.get("value")
441 try:
442 locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep='-')
443 except babel.UnknownLocaleError:
444 print("INFO: google UI language %s (%s) is unknown by babel" % (eng_lang, x.text.split("(")[0].strip()))
445 continue
446 sxng_lang = language_tag(locale)
447
448 conflict = engine_traits.languages.get(sxng_lang)
449 if conflict:
450 if conflict != eng_lang:
451 print("CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
452 continue
453 engine_traits.languages[sxng_lang] = 'lang_' + eng_lang
454
455 # alias languages
456 engine_traits.languages['zh'] = 'lang_zh-CN'
457
458 # supported region codes
459
460 for x in eval_xpath_list(dom, "//select[@name='gl']/option"):
461 eng_country = x.get("value")
462
463 if eng_country in skip_countries:
464 continue
465 if eng_country == 'ZZ':
466 engine_traits.all_locale = 'ZZ'
467 continue
468
469 sxng_locales = get_official_locales(eng_country, engine_traits.languages.keys(), regional=True)
470
471 if not sxng_locales:
472 print("ERROR: can't map from google country %s (%s) to a babel region." % (x.get('data-name'), eng_country))
473 continue
474
475 for sxng_locale in sxng_locales:
476 engine_traits.regions[region_tag(sxng_locale)] = eng_country
477
478 # alias regions
479 engine_traits.regions['zh-CN'] = 'HK'
480
481 # supported domains
482
483 if add_domains:
484 resp = get('https://www.google.com/supported_domains')
485 if not resp.ok: # type: ignore
486 raise RuntimeError("Response from https://www.google.com/supported_domains is not OK.")
487
488 for domain in resp.text.split(): # type: ignore
489 domain = domain.strip()
490 if not domain or domain in [
491 '.google.com',
492 ]:
493 continue
494 region = domain.split('.')[-1].upper()
495 engine_traits.custom['supported_domains'][region] = 'www' + domain # type: ignore
496 if region == 'HK':
497 # There is no google.cn, we use .com.hk for zh-CN
498 engine_traits.custom['supported_domains']['CN'] = 'www' + domain # type: ignore
request(query, params)
Definition google.py:262
get_google_info(params, eng_traits)
Definition google.py:78
fetch_traits(EngineTraits engine_traits, bool add_domains=True)
Definition google.py:424
detect_google_sorry(resp)
Definition google.py:257