.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.engines.google Namespace Reference

Functions

 get_google_info (params, eng_traits)
 
 detect_google_sorry (resp)
 
 request (query, params)
 
 _parse_data_images (dom)
 
 response (resp)
 
 fetch_traits (EngineTraits engine_traits, bool add_domains=True)
 

Variables

logging logger .Logger
 
dict about
 
list categories = ['general', 'web']
 
bool paging = True
 
int max_page = 50
 
bool time_range_support = True
 
bool safesearch = True
 
dict time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
 
dict filter_mapping = {0: 'off', 1: 'medium', 2: 'high'}
 
str results_xpath = './/div[contains(@jscontroller, "SC7lYd")]'
 
str title_xpath = './/a/h3[1]'
 
str href_xpath = './/a[h3]/@href'
 
str content_xpath = './/div[contains(@data-sncf, "1")]'
 
str suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'
 
str UI_ASYNC = 'use_ac:true,_fmt:prog'
 
 RE_DATA_IMAGE = re.compile(r'"(dimg_[^"]*)"[^;]*;(data:image[^;]*;[^;]*);')
 
list skip_countries
 

Detailed Description

This is the implementation of the Google WEB engine.  Some of this
implementations (manly the :py:obj:`get_google_info`) are shared by other
engines:

- :ref:`google images engine`
- :ref:`google news engine`
- :ref:`google videos engine`
- :ref:`google scholar engine`
- :ref:`google autocomplete`

Function Documentation

◆ _parse_data_images()

searx.engines.google._parse_data_images ( dom)
protected

Definition at line 312 of file google.py.

312def _parse_data_images(dom):
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

Referenced by searx.engines.google.response().

+ Here is the caller graph for this function:

◆ detect_google_sorry()

searx.engines.google.detect_google_sorry ( resp)

Definition at line 257 of file google.py.

257def detect_google_sorry(resp):
258 if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
259 raise SearxEngineCaptchaException()
260
261

◆ fetch_traits()

searx.engines.google.fetch_traits ( EngineTraits engine_traits,
bool add_domains = True )
Fetch languages from Google.

Definition at line 424 of file google.py.

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

◆ get_google_info()

searx.engines.google.get_google_info ( params,
eng_traits )
Composing various (language) properties for the google engines (:ref:`google
API`).

This function is called by the various google engines (:ref:`google web
engine`, :ref:`google images engine`, :ref:`google news engine` and
:ref:`google videos engine`).

:param dict param: Request parameters of the engine.  At least
    a ``searxng_locale`` key should be in the dictionary.

:param eng_traits: Engine's traits fetched from google preferences
    (:py:obj:`searx.enginelib.traits.EngineTraits`)

:rtype: dict
:returns:
    Py-Dictionary with the key/value pairs:

    language:
        The language code that is used by google (e.g. ``lang_en`` or
        ``lang_zh-TW``)

    country:
        The country code that is used by google (e.g. ``US`` or ``TW``)

    locale:
        A instance of :py:obj:`babel.core.Locale` build from the
        ``searxng_locale`` value.

    subdomain:
        Google subdomain :py:obj:`google_domains` that fits to the country
        code.

    params:
        Py-Dictionary with additional request arguments (can be passed to
        :py:func:`urllib.parse.urlencode`).

        - ``hl`` parameter: specifies the interface language of user interface.
        - ``lr`` parameter: restricts search results to documents written in
          a particular language.
        - ``cr`` parameter: restricts search results to documents
          originating in a particular country.
        - ``ie`` parameter: sets the character encoding scheme that should
          be used to interpret the query string ('utf8').
        - ``oe`` parameter: sets the character encoding scheme that should
          be used to decode the XML result ('utf8').

    headers:
        Py-Dictionary with additional HTTP headers (can be passed to
        request's headers)

        - ``Accept: '*/*``

Definition at line 78 of file google.py.

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

◆ request()

searx.engines.google.request ( query,
params )
Google search request

Definition at line 262 of file google.py.

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;

◆ response()

searx.engines.google.response ( resp)
Get response from google's search request

Definition at line 323 of file google.py.

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

References searx.engines.google._parse_data_images().

+ Here is the call graph for this function:

Variable Documentation

◆ about

dict searx.engines.google.about
Initial value:
1= {
2 "website": 'https://www.google.com',
3 "wikidata_id": 'Q9366',
4 "official_api_documentation": 'https://developers.google.com/custom-search/',
5 "use_official_api": False,
6 "require_api_key": False,
7 "results": 'HTML',
8}

Definition at line 38 of file google.py.

◆ categories

list searx.engines.google.categories = ['general', 'web']

Definition at line 48 of file google.py.

◆ content_xpath

str searx.engines.google.content_xpath = './/div[contains(@data-sncf, "1")]'

Definition at line 65 of file google.py.

◆ filter_mapping

dict searx.engines.google.filter_mapping = {0: 'off', 1: 'medium', 2: 'high'}

Definition at line 57 of file google.py.

◆ href_xpath

str searx.engines.google.href_xpath = './/a[h3]/@href'

Definition at line 64 of file google.py.

◆ logger

logging searx.engines.google.logger .Logger

Definition at line 32 of file google.py.

◆ max_page

int searx.engines.google.max_page = 50

Definition at line 50 of file google.py.

◆ paging

bool searx.engines.google.paging = True

Definition at line 49 of file google.py.

◆ RE_DATA_IMAGE

searx.engines.google.RE_DATA_IMAGE = re.compile(r'"(dimg_[^"]*)"[^;]*;(data:image[^;]*;[^;]*);')

Definition at line 309 of file google.py.

◆ results_xpath

str searx.engines.google.results_xpath = './/div[contains(@jscontroller, "SC7lYd")]'

Definition at line 62 of file google.py.

◆ safesearch

bool searx.engines.google.safesearch = True

Definition at line 52 of file google.py.

◆ skip_countries

list searx.engines.google.skip_countries
Initial value:
1= [
2 # official language of google-country not in google-languages
3 'AL', # Albanien (sq)
4 'AZ', # Aserbaidschan (az)
5 'BD', # Bangladesch (bn)
6 'BN', # Brunei Darussalam (ms)
7 'BT', # Bhutan (dz)
8 'ET', # Äthiopien (am)
9 'GE', # Georgien (ka, os)
10 'GL', # Grönland (kl)
11 'KH', # Kambodscha (km)
12 'LA', # Laos (lo)
13 'LK', # Sri Lanka (si, ta)
14 'ME', # Montenegro (sr)
15 'MK', # Nordmazedonien (mk, sq)
16 'MM', # Myanmar (my)
17 'MN', # Mongolei (mn)
18 'MV', # Malediven (dv) // dv_MV is unknown by babel
19 'MY', # Malaysia (ms)
20 'NP', # Nepal (ne)
21 'TJ', # Tadschikistan (tg)
22 'TM', # Turkmenistan (tk)
23 'UZ', # Usbekistan (uz)
24]

Definition at line 398 of file google.py.

◆ suggestion_xpath

str searx.engines.google.suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'

Definition at line 69 of file google.py.

◆ time_range_dict

dict searx.engines.google.time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}

Definition at line 54 of file google.py.

◆ time_range_support

bool searx.engines.google.time_range_support = True

Definition at line 51 of file google.py.

◆ title_xpath

str searx.engines.google.title_xpath = './/a/h3[1]'

Definition at line 63 of file google.py.

◆ UI_ASYNC

str searx.engines.google.UI_ASYNC = 'use_ac:true,_fmt:prog'

Definition at line 74 of file google.py.