google.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This is the implementation of the google WEB engine. Some of this
  4. implementations are shared by other engines:
  5. - :ref:`google images engine`
  6. - :ref:`google news engine`
  7. - :ref:`google videos engine`
  8. The google WEB engine itself has a special setup option:
  9. .. code:: yaml
  10. - name: google
  11. ...
  12. use_mobile_ui: false
  13. ``use_mobile_ui``: (default: ``false``)
  14. Enables to use *mobile endpoint* to bypass the google blocking (see
  15. :issue:`159`). On the mobile UI of Google Search, the button :guilabel:`More
  16. results` is not affected by Google rate limiting and we can still do requests
  17. while actively blocked by the original Google search. By activate
  18. ``use_mobile_ui`` this behavior is simulated by adding the parameter
  19. ``async=use_ac:true,_fmt:pc`` to the :py:func:`request`.
  20. """
  21. from urllib.parse import urlencode
  22. from lxml import html
  23. from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
  24. from searx.exceptions import SearxEngineCaptchaException
  25. from searx.enginelib.traits import EngineTraits
  26. traits: EngineTraits
  27. # about
  28. about = {
  29. "website": 'https://www.google.com',
  30. "wikidata_id": 'Q9366',
  31. "official_api_documentation": 'https://developers.google.com/custom-search/',
  32. "use_official_api": False,
  33. "require_api_key": False,
  34. "results": 'HTML',
  35. }
  36. # engine dependent config
  37. categories = ['general', 'web']
  38. paging = True
  39. time_range_support = True
  40. safesearch = True
  41. send_accept_language_header = True
  42. use_mobile_ui = False
  43. supported_languages_url = 'https://www.google.com/preferences?#languages'
  44. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  45. google_domains = {
  46. 'BG': 'google.bg', # Bulgaria
  47. 'CZ': 'google.cz', # Czech Republic
  48. 'DE': 'google.de', # Germany
  49. 'DK': 'google.dk', # Denmark
  50. 'AT': 'google.at', # Austria
  51. 'CH': 'google.ch', # Switzerland
  52. 'GR': 'google.gr', # Greece
  53. 'AU': 'google.com.au', # Australia
  54. 'CA': 'google.ca', # Canada
  55. 'GB': 'google.co.uk', # United Kingdom
  56. 'ID': 'google.co.id', # Indonesia
  57. 'IE': 'google.ie', # Ireland
  58. 'IN': 'google.co.in', # India
  59. 'MY': 'google.com.my', # Malaysia
  60. 'NZ': 'google.co.nz', # New Zealand
  61. 'PH': 'google.com.ph', # Philippines
  62. 'SG': 'google.com.sg', # Singapore
  63. 'US': 'google.com', # United States (google.us) redirects to .com
  64. 'ZA': 'google.co.za', # South Africa
  65. 'AR': 'google.com.ar', # Argentina
  66. 'CL': 'google.cl', # Chile
  67. 'ES': 'google.es', # Spain
  68. 'MX': 'google.com.mx', # Mexico
  69. 'EE': 'google.ee', # Estonia
  70. 'FI': 'google.fi', # Finland
  71. 'BE': 'google.be', # Belgium
  72. 'FR': 'google.fr', # France
  73. 'IL': 'google.co.il', # Israel
  74. 'HR': 'google.hr', # Croatia
  75. 'HU': 'google.hu', # Hungary
  76. 'IT': 'google.it', # Italy
  77. 'JP': 'google.co.jp', # Japan
  78. 'KR': 'google.co.kr', # South Korea
  79. 'LT': 'google.lt', # Lithuania
  80. 'LV': 'google.lv', # Latvia
  81. 'NO': 'google.no', # Norway
  82. 'NL': 'google.nl', # Netherlands
  83. 'PL': 'google.pl', # Poland
  84. 'BR': 'google.com.br', # Brazil
  85. 'PT': 'google.pt', # Portugal
  86. 'RO': 'google.ro', # Romania
  87. 'RU': 'google.ru', # Russia
  88. 'SK': 'google.sk', # Slovakia
  89. 'SI': 'google.si', # Slovenia
  90. 'SE': 'google.se', # Sweden
  91. 'TH': 'google.co.th', # Thailand
  92. 'TR': 'google.com.tr', # Turkey
  93. 'UA': 'google.com.ua', # Ukraine
  94. 'CN': 'google.com.hk', # There is no google.cn, we use .com.hk for zh-CN
  95. 'HK': 'google.com.hk', # Hong Kong
  96. 'TW': 'google.com.tw', # Taiwan
  97. }
  98. time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
  99. # Filter results. 0: None, 1: Moderate, 2: Strict
  100. filter_mapping = {0: 'off', 1: 'medium', 2: 'high'}
  101. # specific xpath variables
  102. # ------------------------
  103. results_xpath = './/div[@data-sokoban-container]'
  104. title_xpath = './/a/h3[1]'
  105. href_xpath = './/a[h3]/@href'
  106. content_xpath = './/div[@data-content-feature=1]'
  107. # google *sections* are no usual *results*, we ignore them
  108. g_section_with_header = './g-section-with-header'
  109. # Suggestions are links placed in a *card-section*, we extract only the text
  110. # from the links not the links itself.
  111. suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'
  112. def get_lang_info(params, lang_list, custom_aliases, supported_any_language):
  113. """Composing various language properties for the google engines.
  114. This function is called by the various google engines (:ref:`google web
  115. engine`, :ref:`google images engine`, :ref:`google news engine` and
  116. :ref:`google videos engine`).
  117. :param dict param: request parameters of the engine
  118. :param list lang_list: list of supported languages of the engine
  119. :py:obj:`ENGINES_LANGUAGES[engine-name] <searx.data.ENGINES_LANGUAGES>`
  120. :param dict lang_list: custom aliases for non standard language codes
  121. (used when calling :py:func:`searx.utils.match_language`)
  122. :param bool supported_any_language: When a language is not specified, the
  123. language interpretation is left up to Google to decide how the search
  124. results should be delivered. This argument is ``True`` for the google
  125. engine and ``False`` for the other engines (google-images, -news,
  126. -scholar, -videos).
  127. :rtype: dict
  128. :returns:
  129. Py-Dictionary with the key/value pairs:
  130. language:
  131. Return value from :py:func:`searx.utils.match_language`
  132. country:
  133. The country code (e.g. US, AT, CA, FR, DE ..)
  134. subdomain:
  135. Google subdomain :py:obj:`google_domains` that fits to the country
  136. code.
  137. params:
  138. Py-Dictionary with additional request arguments (can be passed to
  139. :py:func:`urllib.parse.urlencode`).
  140. headers:
  141. Py-Dictionary with additional HTTP headers (can be passed to
  142. request's headers)
  143. """
  144. ret_val = {
  145. 'language': None,
  146. 'country': None,
  147. 'subdomain': None,
  148. 'params': {},
  149. 'headers': {},
  150. }
  151. # language ...
  152. _lang = params['language']
  153. _any_language = _lang.lower() == 'all'
  154. if _any_language:
  155. _lang = 'en-US'
  156. language = match_language(_lang, lang_list, custom_aliases)
  157. ret_val['language'] = language
  158. # country ...
  159. _l = _lang.split('-')
  160. if len(_l) == 2:
  161. country = _l[1]
  162. else:
  163. country = _l[0].upper()
  164. if country == 'EN':
  165. country = 'US'
  166. ret_val['country'] = country
  167. # subdomain ...
  168. ret_val['subdomain'] = 'www.' + google_domains.get(country.upper(), 'google.com')
  169. # params & headers
  170. lang_country = '%s-%s' % (language, country) # (en-US, en-EN, de-DE, de-AU, fr-FR ..)
  171. # hl parameter:
  172. # https://developers.google.com/custom-search/docs/xml_results#hlsp The
  173. # Interface Language:
  174. # https://developers.google.com/custom-search/docs/xml_results_appendices#interfaceLanguages
  175. ret_val['params']['hl'] = lang_list.get(lang_country, language)
  176. # lr parameter:
  177. # The lr (language restrict) parameter restricts search results to
  178. # documents written in a particular language.
  179. # https://developers.google.com/custom-search/docs/xml_results#lrsp
  180. # Language Collection Values:
  181. # https://developers.google.com/custom-search/docs/xml_results_appendices#languageCollections
  182. if _any_language and supported_any_language:
  183. # interpretation is left up to Google (based on whoogle)
  184. #
  185. # - add parameter ``source=lnt``
  186. # - don't use parameter ``lr``
  187. # - don't add a ``Accept-Language`` HTTP header.
  188. ret_val['params']['source'] = 'lnt'
  189. else:
  190. # restricts search results to documents written in a particular
  191. # language.
  192. ret_val['params']['lr'] = "lang_" + lang_list.get(lang_country, language)
  193. return ret_val
  194. def detect_google_sorry(resp):
  195. if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
  196. raise SearxEngineCaptchaException()
  197. def request(query, params):
  198. """Google search request"""
  199. offset = (params['pageno'] - 1) * 10
  200. lang_info = get_lang_info(params, supported_languages, language_aliases, True)
  201. additional_parameters = {}
  202. if use_mobile_ui:
  203. additional_parameters = {
  204. 'asearch': 'arc',
  205. 'async': 'use_ac:true,_fmt:prog',
  206. }
  207. # https://www.google.de/search?q=corona&hl=de&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  208. query_url = (
  209. 'https://'
  210. + lang_info['subdomain']
  211. + '/search'
  212. + "?"
  213. + urlencode(
  214. {
  215. 'q': query,
  216. **lang_info['params'],
  217. 'ie': "utf8",
  218. 'oe': "utf8",
  219. 'start': offset,
  220. 'filter': '0',
  221. **additional_parameters,
  222. }
  223. )
  224. )
  225. if params['time_range'] in time_range_dict:
  226. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  227. if params['safesearch']:
  228. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  229. params['url'] = query_url
  230. params['cookies']['CONSENT'] = "YES+"
  231. params['headers'].update(lang_info['headers'])
  232. if use_mobile_ui:
  233. params['headers']['Accept'] = '*/*'
  234. else:
  235. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  236. return params
  237. def response(resp):
  238. """Get response from google's search request"""
  239. detect_google_sorry(resp)
  240. results = []
  241. # convert the text to dom
  242. dom = html.fromstring(resp.text)
  243. # results --> answer
  244. answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
  245. if answer_list:
  246. answer_list = [_.xpath("normalize-space()") for _ in answer_list]
  247. results.append({'answer': ' '.join(answer_list)})
  248. else:
  249. logger.debug("did not find 'answer'")
  250. # results --> number_of_results
  251. if not use_mobile_ui:
  252. try:
  253. _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
  254. _digit = ''.join([n for n in _txt if n.isdigit()])
  255. number_of_results = int(_digit)
  256. results.append({'number_of_results': number_of_results})
  257. except Exception as e: # pylint: disable=broad-except
  258. logger.debug("did not 'number_of_results'")
  259. logger.error(e, exc_info=True)
  260. # parse results
  261. for result in eval_xpath_list(dom, results_xpath):
  262. # google *sections*
  263. if extract_text(eval_xpath(result, g_section_with_header)):
  264. logger.debug("ignoring <g-section-with-header>")
  265. continue
  266. try:
  267. title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
  268. if title_tag is None:
  269. # this not one of the common google results *section*
  270. logger.debug('ignoring item from the result_xpath list: missing title')
  271. continue
  272. title = extract_text(title_tag)
  273. url = eval_xpath_getindex(result, href_xpath, 0, None)
  274. if url is None:
  275. continue
  276. content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
  277. if content is None:
  278. logger.debug('ignoring item from the result_xpath list: missing content of title "%s"', title)
  279. continue
  280. logger.debug('add link to results: %s', title)
  281. results.append({'url': url, 'title': title, 'content': content})
  282. except Exception as e: # pylint: disable=broad-except
  283. logger.error(e, exc_info=True)
  284. continue
  285. # parse suggestion
  286. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  287. # append suggestion
  288. results.append({'suggestion': extract_text(suggestion)})
  289. # return results
  290. return results
  291. # get supported languages from their site
  292. def _fetch_supported_languages(resp):
  293. ret_val = {}
  294. dom = html.fromstring(resp.text)
  295. radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
  296. for x in radio_buttons:
  297. name = x.get("data-name")
  298. code = x.get("value").split('_')[-1]
  299. ret_val[code] = {"name": name}
  300. return ret_val
  301. skip_countries = [
  302. # official language of google-country not in google-languages
  303. 'AL', # Albanien (sq)
  304. 'AZ', # Aserbaidschan (az)
  305. 'BD', # Bangladesch (bn)
  306. 'BN', # Brunei Darussalam (ms)
  307. 'BT', # Bhutan (dz)
  308. 'ET', # Äthiopien (am)
  309. 'GE', # Georgien (ka, os)
  310. 'GL', # Grönland (kl)
  311. 'KH', # Kambodscha (km)
  312. 'LA', # Laos (lo)
  313. 'LK', # Sri Lanka (si, ta)
  314. 'ME', # Montenegro (sr)
  315. 'MK', # Nordmazedonien (mk, sq)
  316. 'MM', # Myanmar (my)
  317. 'MN', # Mongolei (mn)
  318. 'MV', # Malediven (dv) // dv_MV is unknown by babel
  319. 'MY', # Malaysia (ms)
  320. 'NP', # Nepal (ne)
  321. 'TJ', # Tadschikistan (tg)
  322. 'TM', # Turkmenistan (tk)
  323. 'UZ', # Usbekistan (uz)
  324. ]
  325. def fetch_traits(engine_traits: EngineTraits):
  326. """Fetch languages from Google."""
  327. # pylint: disable=import-outside-toplevel
  328. engine_traits.data_type = 'supported_languages' # deprecated
  329. import babel
  330. import babel.languages
  331. from searx import network
  332. from searx.locales import language_tag, region_tag, get_offical_locales
  333. resp = network.get('https://www.google.com/preferences')
  334. if not resp.ok:
  335. print("ERROR: response from Google is not OK.")
  336. dom = html.fromstring(resp.text)
  337. lang_map = {'no': 'nb'}
  338. for x in eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]'):
  339. eng_lang = x.get("value").split('_')[-1]
  340. try:
  341. locale = babel.Locale.parse(lang_map.get(eng_lang, eng_lang), sep='-')
  342. except babel.UnknownLocaleError:
  343. print("ERROR: %s -> %s is unknown by babel" % (x.get("data-name"), eng_lang))
  344. continue
  345. sxng_lang = language_tag(locale)
  346. conflict = engine_traits.languages.get(sxng_lang)
  347. if conflict:
  348. if conflict != eng_lang:
  349. print("CONFLICT: babel %s --> %s, %s" % (sxng_lang, conflict, eng_lang))
  350. continue
  351. engine_traits.languages[sxng_lang] = 'lang_' + eng_lang
  352. # alias languages
  353. engine_traits.languages['zh'] = 'lang_zh-CN'
  354. for x in eval_xpath_list(dom, '//*[@name="region"]/..//input[@name="region"]'):
  355. eng_country = x.get("value")
  356. if eng_country in skip_countries:
  357. continue
  358. if eng_country == 'ZZ':
  359. engine_traits.all_locale = 'ZZ'
  360. continue
  361. sxng_locales = get_offical_locales(eng_country, engine_traits.languages.keys(), regional=True)
  362. if not sxng_locales:
  363. print("ERROR: can't map from google country %s (%s) to a babel region." % (x.get('data-name'), eng_country))
  364. continue
  365. for sxng_locale in sxng_locales:
  366. engine_traits.regions[region_tag(sxng_locale)] = 'country' + eng_country