.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[@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 results.append(
338 {
339 'answer': item.xpath("normalize-space()"),
340 'url': (eval_xpath(item, '../..//a/@href') + [None])[0],
341 }
342 )
343
344 # parse results
345
346 for result in eval_xpath_list(dom, results_xpath): # pylint: disable=too-many-nested-blocks
347
348 try:
349 title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
350 if title_tag is None:
351 # this not one of the common google results *section*
352 logger.debug('ignoring item from the result_xpath list: missing title')
353 continue
354 title = extract_text(title_tag)
355
356 url = eval_xpath_getindex(result, href_xpath, 0, None)
357 if url is None:
358 logger.debug('ignoring item from the result_xpath list: missing url of title "%s"', title)
359 continue
360
361 content_nodes = eval_xpath(result, content_xpath)
362 content = extract_text(content_nodes)
363
364 if not content:
365 logger.debug('ignoring item from the result_xpath list: missing content of title "%s"', title)
366 continue
367
368 img_src = content_nodes[0].xpath('.//img/@src')
369 if img_src:
370 img_src = img_src[0]
371 if img_src.startswith('data:image'):
372 img_id = content_nodes[0].xpath('.//img/@id')
373 if img_id:
374 img_src = data_image_map.get(img_id[0])
375 else:
376 img_src = None
377
378 results.append({'url': url, 'title': title, 'content': content, 'img_src': img_src})
379
380 except Exception as e: # pylint: disable=broad-except
381 logger.error(e, exc_info=True)
382 continue
383
384 # parse suggestion
385 for suggestion in eval_xpath_list(dom, suggestion_xpath):
386 # append suggestion
387 results.append({'suggestion': extract_text(suggestion)})
388
389 # return results
390 return results
391
392
393# get supported languages from their site
394
395
396skip_countries = [
397 # official language of google-country not in google-languages
398 'AL', # Albanien (sq)
399 'AZ', # Aserbaidschan (az)
400 'BD', # Bangladesch (bn)
401 'BN', # Brunei Darussalam (ms)
402 'BT', # Bhutan (dz)
403 'ET', # Äthiopien (am)
404 'GE', # Georgien (ka, os)
405 'GL', # Grönland (kl)
406 'KH', # Kambodscha (km)
407 'LA', # Laos (lo)
408 'LK', # Sri Lanka (si, ta)
409 'ME', # Montenegro (sr)
410 'MK', # Nordmazedonien (mk, sq)
411 'MM', # Myanmar (my)
412 'MN', # Mongolei (mn)
413 'MV', # Malediven (dv) // dv_MV is unknown by babel
414 'MY', # Malaysia (ms)
415 'NP', # Nepal (ne)
416 'TJ', # Tadschikistan (tg)
417 'TM', # Turkmenistan (tk)
418 'UZ', # Usbekistan (uz)
419]
420
421
422def fetch_traits(engine_traits: EngineTraits, add_domains: bool = True):
423 """Fetch languages from Google."""
424 # pylint: disable=import-outside-toplevel, too-many-branches
425
426 engine_traits.custom['supported_domains'] = {}
427
428 resp = get('https://www.google.com/preferences')
429 if not resp.ok: # type: ignore
430 raise RuntimeError("Response from Google's preferences is not OK.")
431
432 dom = html.fromstring(resp.text.replace('<?xml version="1.0" encoding="UTF-8"?>', ''))
433
434 # supported language codes
435
436 lang_map = {'no': 'nb'}
437 for x in eval_xpath_list(dom, "//select[@name='hl']/option"):
438 eng_lang = x.get("value")
439 try:
440 locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep='-')
441 except babel.UnknownLocaleError:
442 print("ERROR: %s -> %s is unknown by babel" % (x.get("data-name"), eng_lang))
443 continue
444 sxng_lang = language_tag(locale)
445
446 conflict = engine_traits.languages.get(sxng_lang)
447 if conflict:
448 if conflict != eng_lang:
449 print("CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
450 continue
451 engine_traits.languages[sxng_lang] = 'lang_' + eng_lang
452
453 # alias languages
454 engine_traits.languages['zh'] = 'lang_zh-CN'
455
456 # supported region codes
457
458 for x in eval_xpath_list(dom, "//select[@name='gl']/option"):
459 eng_country = x.get("value")
460
461 if eng_country in skip_countries:
462 continue
463 if eng_country == 'ZZ':
464 engine_traits.all_locale = 'ZZ'
465 continue
466
467 sxng_locales = get_official_locales(eng_country, engine_traits.languages.keys(), regional=True)
468
469 if not sxng_locales:
470 print("ERROR: can't map from google country %s (%s) to a babel region." % (x.get('data-name'), eng_country))
471 continue
472
473 for sxng_locale in sxng_locales:
474 engine_traits.regions[region_tag(sxng_locale)] = eng_country
475
476 # alias regions
477 engine_traits.regions['zh-CN'] = 'HK'
478
479 # supported domains
480
481 if add_domains:
482 resp = get('https://www.google.com/supported_domains')
483 if not resp.ok: # type: ignore
484 raise RuntimeError("Response from https://www.google.com/supported_domains is not OK.")
485
486 for domain in resp.text.split(): # type: ignore
487 domain = domain.strip()
488 if not domain or domain in [
489 '.google.com',
490 ]:
491 continue
492 region = domain.split('.')[-1].upper()
493 engine_traits.custom['supported_domains'][region] = 'www' + domain # type: ignore
494 if region == 'HK':
495 # There is no google.cn, we use .com.hk for zh-CN
496 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:422
detect_google_sorry(resp)
Definition google.py:257