71 """Format of the response from UI's async request.
73 - ``arc_id:<...>,use_ac:true,_fmt:prog``
75 The arc_id is random generated every hour.
79 use_ac =
"use_ac:true"
85 if not _arcid_random
or (int(time.time()) - _arcid_random[1]) > 3600:
86 _arcid_random = (
''.join(random.choices(_arcid_range, k=23)), int(time.time()))
87 arc_id = f
"arc_id:srp_{_arcid_random[0]}_1{start:02}"
89 return ",".join([arc_id, use_ac, _fmt])
93 """Composing various (language) properties for the google engines (:ref:`google
96 This function is called by the various google engines (:ref:`google web
97 engine`, :ref:`google images engine`, :ref:`google news engine` and
98 :ref:`google videos engine`).
100 :param dict param: Request parameters of the engine. At least
101 a ``searxng_locale`` key should be in the dictionary.
103 :param eng_traits: Engine's traits fetched from google preferences
104 (:py:obj:`searx.enginelib.traits.EngineTraits`)
108 Py-Dictionary with the key/value pairs:
111 The language code that is used by google (e.g. ``lang_en`` or
115 The country code that is used by google (e.g. ``US`` or ``TW``)
118 A instance of :py:obj:`babel.core.Locale` build from the
119 ``searxng_locale`` value.
122 Google subdomain :py:obj:`google_domains` that fits to the country
126 Py-Dictionary with additional request arguments (can be passed to
127 :py:func:`urllib.parse.urlencode`).
129 - ``hl`` parameter: specifies the interface language of user interface.
130 - ``lr`` parameter: restricts search results to documents written in
131 a particular language.
132 - ``cr`` parameter: restricts search results to documents
133 originating in a particular country.
134 - ``ie`` parameter: sets the character encoding scheme that should
135 be used to interpret the query string ('utf8').
136 - ``oe`` parameter: sets the character encoding scheme that should
137 be used to decode the XML result ('utf8').
140 Py-Dictionary with additional HTTP headers (can be passed to
157 sxng_locale = params.get(
'searxng_locale',
'all')
159 locale = babel.Locale.parse(sxng_locale, sep=
'-')
160 except babel.core.UnknownLocaleError:
163 eng_lang = eng_traits.get_language(sxng_locale,
'lang_en')
164 lang_code = eng_lang.split(
'_')[-1]
165 country = eng_traits.get_region(sxng_locale, eng_traits.all_locale)
175 ret_val[
'language'] = eng_lang
176 ret_val[
'country'] = country
177 ret_val[
'locale'] = locale
178 ret_val[
'subdomain'] = eng_traits.custom[
'supported_domains'].get(country.upper(),
'www.google.com')
190 ret_val[
'params'][
'hl'] = f
'{lang_code}-{country}'
206 ret_val[
'params'][
'lr'] = eng_lang
207 if sxng_locale ==
'all':
208 ret_val[
'params'][
'lr'] =
''
217 ret_val[
'params'][
'cr'] =
''
218 if len(sxng_locale.split(
'-')) > 1:
219 ret_val[
'params'][
'cr'] =
'country' + country
240 ret_val[
'params'][
'ie'] =
'utf8'
247 ret_val[
'params'][
'oe'] =
'utf8'
260 ret_val[
'headers'][
'Accept'] =
'*/*'
266 ret_val[
'cookies'][
'CONSENT'] =
"YES+"
332 for img_id, data_image
in RE_DATA_IMAGE.findall(text):
333 end_pos = data_image.rfind(
'=')
335 data_image = data_image[: end_pos + 1]
336 data_image_map[img_id] = data_image
337 last = RE_DATA_IMAGE_end.search(text)
339 data_image_map[last.group(1)] = last.group(2)
340 logger.debug(
'data:image objects --> %s', list(data_image_map.keys()))
341 return data_image_map
345 """Get response from google's search request"""
353 dom = html.fromstring(resp.text)
356 answer_list = eval_xpath(dom,
'//div[contains(@class, "LGOjhe")]')
357 for item
in answer_list:
358 for bubble
in eval_xpath(item,
'.//div[@class="nnFGuf"]'):
361 results.types.Answer(
362 answer=extract_text(item),
363 url=(eval_xpath(item,
'../..//a/@href') + [
None])[0],
369 for result
in eval_xpath_list(dom,
'.//div[contains(@jscontroller, "SC7lYd")]'):
373 title_tag = eval_xpath_getindex(result,
'.//a/h3[1]', 0, default=
None)
374 if title_tag
is None:
376 logger.debug(
'ignoring item from the result_xpath list: missing title')
378 title = extract_text(title_tag)
380 url = eval_xpath_getindex(result,
'.//a[h3]/@href', 0,
None)
382 logger.debug(
'ignoring item from the result_xpath list: missing url of title "%s"', title)
385 content_nodes = eval_xpath(result,
'.//div[contains(@data-sncf, "1")]')
386 for item
in content_nodes:
387 for script
in item.xpath(
".//script"):
388 script.getparent().remove(script)
390 content = extract_text(content_nodes)
393 logger.debug(
'ignoring item from the result_xpath list: missing content of title "%s"', title)
396 thumbnail = content_nodes[0].xpath(
'.//img/@src')
398 thumbnail = thumbnail[0]
399 if thumbnail.startswith(
'data:image'):
400 img_id = content_nodes[0].xpath(
'.//img/@id')
402 thumbnail = data_image_map.get(img_id[0])
406 results.append({
'url': url,
'title': title,
'content': content,
'thumbnail': thumbnail})
408 except Exception
as e:
409 logger.error(e, exc_info=
True)
413 for suggestion
in eval_xpath_list(dom, suggestion_xpath):
415 results.append({
'suggestion': extract_text(suggestion)})
450def fetch_traits(engine_traits: EngineTraits, add_domains: bool =
True):
451 """Fetch languages from Google."""
454 engine_traits.custom[
'supported_domains'] = {}
456 resp = get(
'https://www.google.com/preferences')
458 raise RuntimeError(
"Response from Google's preferences is not OK.")
460 dom = html.fromstring(resp.text.replace(
'<?xml version="1.0" encoding="UTF-8"?>',
''))
464 lang_map = {
'no':
'nb'}
465 for x
in eval_xpath_list(dom,
"//select[@name='hl']/option"):
466 eng_lang = x.get(
"value")
468 locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep=
'-')
469 except babel.UnknownLocaleError:
470 print(
"INFO: google UI language %s (%s) is unknown by babel" % (eng_lang, x.text.split(
"(")[0].strip()))
472 sxng_lang = language_tag(locale)
474 conflict = engine_traits.languages.get(sxng_lang)
476 if conflict != eng_lang:
477 print(
"CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
479 engine_traits.languages[sxng_lang] =
'lang_' + eng_lang
482 engine_traits.languages[
'zh'] =
'lang_zh-CN'
486 for x
in eval_xpath_list(dom,
"//select[@name='gl']/option"):
487 eng_country = x.get(
"value")
489 if eng_country
in skip_countries:
491 if eng_country ==
'ZZ':
492 engine_traits.all_locale =
'ZZ'
495 sxng_locales = get_official_locales(eng_country, engine_traits.languages.keys(), regional=
True)
498 print(
"ERROR: can't map from google country %s (%s) to a babel region." % (x.get(
'data-name'), eng_country))
501 for sxng_locale
in sxng_locales:
502 engine_traits.regions[region_tag(sxng_locale)] = eng_country
505 engine_traits.regions[
'zh-CN'] =
'HK'
510 resp = get(
'https://www.google.com/supported_domains')
512 raise RuntimeError(
"Response from https://www.google.com/supported_domains is not OK.")
514 for domain
in resp.text.split():
515 domain = domain.strip()
516 if not domain
or domain
in [
520 region = domain.split(
'.')[-1].upper()
521 engine_traits.custom[
'supported_domains'][region] =
'www' + domain
524 engine_traits.custom[
'supported_domains'][
'CN'] =
'www' + domain