google.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. # about
  26. about = {
  27. "website": 'https://www.google.com',
  28. "wikidata_id": 'Q9366',
  29. "official_api_documentation": 'https://developers.google.com/custom-search/',
  30. "use_official_api": False,
  31. "require_api_key": False,
  32. "results": 'HTML',
  33. }
  34. # engine dependent config
  35. categories = ['general', 'web']
  36. paging = True
  37. time_range_support = True
  38. safesearch = True
  39. send_accept_language_header = True
  40. use_mobile_ui = False
  41. supported_languages_url = 'https://www.google.com/preferences?#languages'
  42. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  43. google_domains = {
  44. 'BG': 'google.bg', # Bulgaria
  45. 'CZ': 'google.cz', # Czech Republic
  46. 'DE': 'google.de', # Germany
  47. 'DK': 'google.dk', # Denmark
  48. 'AT': 'google.at', # Austria
  49. 'CH': 'google.ch', # Switzerland
  50. 'GR': 'google.gr', # Greece
  51. 'AU': 'google.com.au', # Australia
  52. 'CA': 'google.ca', # Canada
  53. 'GB': 'google.co.uk', # United Kingdom
  54. 'ID': 'google.co.id', # Indonesia
  55. 'IE': 'google.ie', # Ireland
  56. 'IN': 'google.co.in', # India
  57. 'MY': 'google.com.my', # Malaysia
  58. 'NZ': 'google.co.nz', # New Zealand
  59. 'PH': 'google.com.ph', # Philippines
  60. 'SG': 'google.com.sg', # Singapore
  61. 'US': 'google.com', # United States (google.us) redirects to .com
  62. 'ZA': 'google.co.za', # South Africa
  63. 'AR': 'google.com.ar', # Argentina
  64. 'CL': 'google.cl', # Chile
  65. 'ES': 'google.es', # Spain
  66. 'MX': 'google.com.mx', # Mexico
  67. 'EE': 'google.ee', # Estonia
  68. 'FI': 'google.fi', # Finland
  69. 'BE': 'google.be', # Belgium
  70. 'FR': 'google.fr', # France
  71. 'IL': 'google.co.il', # Israel
  72. 'HR': 'google.hr', # Croatia
  73. 'HU': 'google.hu', # Hungary
  74. 'IT': 'google.it', # Italy
  75. 'JP': 'google.co.jp', # Japan
  76. 'KR': 'google.co.kr', # South Korea
  77. 'LT': 'google.lt', # Lithuania
  78. 'LV': 'google.lv', # Latvia
  79. 'NO': 'google.no', # Norway
  80. 'NL': 'google.nl', # Netherlands
  81. 'PL': 'google.pl', # Poland
  82. 'BR': 'google.com.br', # Brazil
  83. 'PT': 'google.pt', # Portugal
  84. 'RO': 'google.ro', # Romania
  85. 'RU': 'google.ru', # Russia
  86. 'SK': 'google.sk', # Slovakia
  87. 'SI': 'google.si', # Slovenia
  88. 'SE': 'google.se', # Sweden
  89. 'TH': 'google.co.th', # Thailand
  90. 'TR': 'google.com.tr', # Turkey
  91. 'UA': 'google.com.ua', # Ukraine
  92. 'CN': 'google.com.hk', # There is no google.cn, we use .com.hk for zh-CN
  93. 'HK': 'google.com.hk', # Hong Kong
  94. 'TW': 'google.com.tw', # Taiwan
  95. }
  96. time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
  97. # Filter results. 0: None, 1: Moderate, 2: Strict
  98. filter_mapping = {0: 'off', 1: 'medium', 2: 'high'}
  99. # specific xpath variables
  100. # ------------------------
  101. # google results are grouped into <div class="jtfYYd ..." ../>
  102. results_xpath = '//div[contains(@class, "jtfYYd")]'
  103. # google *sections* are no usual *results*, we ignore them
  104. g_section_with_header = './g-section-with-header'
  105. # the title is a h3 tag relative to the result group
  106. title_xpath = './/h3[1]'
  107. # in the result group there is <div class="yuRUbf" ../> it's first child is a <a
  108. # href=...>
  109. href_xpath = './/div[@class="yuRUbf"]//a/@href'
  110. # in the result group there is <div class="VwiC3b ..." ../> containing the *content*
  111. content_xpath = './/div[contains(@class, "VwiC3b")]'
  112. # Suggestions are links placed in a *card-section*, we extract only the text
  113. # from the links not the links itself.
  114. suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'
  115. def get_lang_info(params, lang_list, custom_aliases, supported_any_language):
  116. """Composing various language properties for the google engines.
  117. This function is called by the various google engines (:ref:`google web
  118. engine`, :ref:`google images engine`, :ref:`google news engine` and
  119. :ref:`google videos engine`).
  120. :param dict param: request parameters of the engine
  121. :param list lang_list: list of supported languages of the engine
  122. :py:obj:`ENGINES_LANGUAGES[engine-name] <searx.data.ENGINES_LANGUAGES>`
  123. :param dict lang_list: custom aliases for non standard language codes
  124. (used when calling :py:func:`searx.utils.match_language`)
  125. :param bool supported_any_language: When a language is not specified, the
  126. language interpretation is left up to Google to decide how the search
  127. results should be delivered. This argument is ``True`` for the google
  128. engine and ``False`` for the other engines (google-images, -news,
  129. -scholar, -videos).
  130. :rtype: dict
  131. :returns:
  132. Py-Dictionary with the key/value pairs:
  133. language:
  134. Return value from :py:func:`searx.utils.match_language`
  135. country:
  136. The country code (e.g. US, AT, CA, FR, DE ..)
  137. subdomain:
  138. Google subdomain :py:obj:`google_domains` that fits to the country
  139. code.
  140. params:
  141. Py-Dictionary with additional request arguments (can be passed to
  142. :py:func:`urllib.parse.urlencode`).
  143. headers:
  144. Py-Dictionary with additional HTTP headers (can be passed to
  145. request's headers)
  146. """
  147. ret_val = {
  148. 'language': None,
  149. 'country': None,
  150. 'subdomain': None,
  151. 'params': {},
  152. 'headers': {},
  153. }
  154. # language ...
  155. _lang = params['language']
  156. _any_language = _lang.lower() == 'all'
  157. if _any_language:
  158. _lang = 'en-US'
  159. language = match_language(_lang, lang_list, custom_aliases)
  160. ret_val['language'] = language
  161. # country ...
  162. _l = _lang.split('-')
  163. if len(_l) == 2:
  164. country = _l[1]
  165. else:
  166. country = _l[0].upper()
  167. if country == 'EN':
  168. country = 'US'
  169. ret_val['country'] = country
  170. # subdomain ...
  171. ret_val['subdomain'] = 'www.' + google_domains.get(country.upper(), 'google.com')
  172. # params & headers
  173. lang_country = '%s-%s' % (language, country) # (en-US, en-EN, de-DE, de-AU, fr-FR ..)
  174. # hl parameter:
  175. # https://developers.google.com/custom-search/docs/xml_results#hlsp The
  176. # Interface Language:
  177. # https://developers.google.com/custom-search/docs/xml_results_appendices#interfaceLanguages
  178. ret_val['params']['hl'] = lang_list.get(lang_country, language)
  179. # lr parameter:
  180. # The lr (language restrict) parameter restricts search results to
  181. # documents written in a particular language.
  182. # https://developers.google.com/custom-search/docs/xml_results#lrsp
  183. # Language Collection Values:
  184. # https://developers.google.com/custom-search/docs/xml_results_appendices#languageCollections
  185. if _any_language and supported_any_language:
  186. # interpretation is left up to Google (based on whoogle)
  187. #
  188. # - add parameter ``source=lnt``
  189. # - don't use parameter ``lr``
  190. # - don't add a ``Accept-Language`` HTTP header.
  191. ret_val['params']['source'] = 'lnt'
  192. else:
  193. # restricts search results to documents written in a particular
  194. # language.
  195. ret_val['params']['lr'] = "lang_" + lang_list.get(lang_country, language)
  196. return ret_val
  197. def detect_google_sorry(resp):
  198. if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
  199. raise SearxEngineCaptchaException()
  200. def request(query, params):
  201. """Google search request"""
  202. offset = (params['pageno'] - 1) * 10
  203. lang_info = get_lang_info(params, supported_languages, language_aliases, True)
  204. additional_parameters = {}
  205. if use_mobile_ui:
  206. additional_parameters = {
  207. 'asearch': 'arc',
  208. 'async': 'use_ac:true,_fmt:pc',
  209. }
  210. # https://www.google.de/search?q=corona&hl=de&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  211. query_url = (
  212. 'https://'
  213. + lang_info['subdomain']
  214. + '/search'
  215. + "?"
  216. + urlencode(
  217. {
  218. 'q': query,
  219. **lang_info['params'],
  220. 'ie': "utf8",
  221. 'oe': "utf8",
  222. 'start': offset,
  223. 'filter': '0',
  224. **additional_parameters,
  225. }
  226. )
  227. )
  228. if params['time_range'] in time_range_dict:
  229. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  230. if params['safesearch']:
  231. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  232. params['url'] = query_url
  233. params['cookies']['CONSENT'] = "YES+"
  234. params['headers'].update(lang_info['headers'])
  235. if use_mobile_ui:
  236. params['headers']['Accept'] = '*/*'
  237. else:
  238. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  239. return params
  240. def response(resp):
  241. """Get response from google's search request"""
  242. detect_google_sorry(resp)
  243. results = []
  244. # convert the text to dom
  245. dom = html.fromstring(resp.text)
  246. # results --> answer
  247. answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
  248. if answer_list:
  249. answer_list = [_.xpath("normalize-space()") for _ in answer_list]
  250. results.append({'answer': ' '.join(answer_list)})
  251. else:
  252. logger.debug("did not find 'answer'")
  253. # results --> number_of_results
  254. if not use_mobile_ui:
  255. try:
  256. _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
  257. _digit = ''.join([n for n in _txt if n.isdigit()])
  258. number_of_results = int(_digit)
  259. results.append({'number_of_results': number_of_results})
  260. except Exception as e: # pylint: disable=broad-except
  261. logger.debug("did not 'number_of_results'")
  262. logger.error(e, exc_info=True)
  263. # parse results
  264. for result in eval_xpath_list(dom, results_xpath):
  265. # google *sections*
  266. if extract_text(eval_xpath(result, g_section_with_header)):
  267. logger.debug("ingoring <g-section-with-header>")
  268. continue
  269. try:
  270. title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
  271. if title_tag is None:
  272. # this not one of the common google results *section*
  273. logger.debug('ingoring item from the result_xpath list: missing title')
  274. continue
  275. title = extract_text(title_tag)
  276. url = eval_xpath_getindex(result, href_xpath, 0, None)
  277. if url is None:
  278. continue
  279. content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
  280. if content is None:
  281. logger.debug('ingoring item from the result_xpath list: missing content of title "%s"', title)
  282. continue
  283. logger.debug('add link to results: %s', title)
  284. results.append({'url': url, 'title': title, 'content': content})
  285. except Exception as e: # pylint: disable=broad-except
  286. logger.error(e, exc_info=True)
  287. continue
  288. # parse suggestion
  289. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  290. # append suggestion
  291. results.append({'suggestion': extract_text(suggestion)})
  292. # return results
  293. return results
  294. # get supported languages from their site
  295. def _fetch_supported_languages(resp):
  296. ret_val = {}
  297. dom = html.fromstring(resp.text)
  298. radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
  299. for x in radio_buttons:
  300. name = x.get("data-name")
  301. code = x.get("value").split('_')[-1]
  302. ret_val[code] = {"name": name}
  303. return ret_val