google.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. results_xpath = '//div[contains(@class, "MjjYud")]'
  102. title_xpath = './/h3[1]'
  103. href_xpath = './/a/@href'
  104. content_xpath = './/div[@data-content-feature=1]'
  105. # google *sections* are no usual *results*, we ignore them
  106. g_section_with_header = './g-section-with-header'
  107. # Suggestions are links placed in a *card-section*, we extract only the text
  108. # from the links not the links itself.
  109. suggestion_xpath = '//div[contains(@class, "EIaa9b")]//a'
  110. def get_lang_info(params, lang_list, custom_aliases, supported_any_language):
  111. """Composing various language properties for the google engines.
  112. This function is called by the various google engines (:ref:`google web
  113. engine`, :ref:`google images engine`, :ref:`google news engine` and
  114. :ref:`google videos engine`).
  115. :param dict param: request parameters of the engine
  116. :param list lang_list: list of supported languages of the engine
  117. :py:obj:`ENGINES_LANGUAGES[engine-name] <searx.data.ENGINES_LANGUAGES>`
  118. :param dict lang_list: custom aliases for non standard language codes
  119. (used when calling :py:func:`searx.utils.match_language`)
  120. :param bool supported_any_language: When a language is not specified, the
  121. language interpretation is left up to Google to decide how the search
  122. results should be delivered. This argument is ``True`` for the google
  123. engine and ``False`` for the other engines (google-images, -news,
  124. -scholar, -videos).
  125. :rtype: dict
  126. :returns:
  127. Py-Dictionary with the key/value pairs:
  128. language:
  129. Return value from :py:func:`searx.utils.match_language`
  130. country:
  131. The country code (e.g. US, AT, CA, FR, DE ..)
  132. subdomain:
  133. Google subdomain :py:obj:`google_domains` that fits to the country
  134. code.
  135. params:
  136. Py-Dictionary with additional request arguments (can be passed to
  137. :py:func:`urllib.parse.urlencode`).
  138. headers:
  139. Py-Dictionary with additional HTTP headers (can be passed to
  140. request's headers)
  141. """
  142. ret_val = {
  143. 'language': None,
  144. 'country': None,
  145. 'subdomain': None,
  146. 'params': {},
  147. 'headers': {},
  148. }
  149. # language ...
  150. _lang = params['language']
  151. _any_language = _lang.lower() == 'all'
  152. if _any_language:
  153. _lang = 'en-US'
  154. language = match_language(_lang, lang_list, custom_aliases)
  155. ret_val['language'] = language
  156. # country ...
  157. _l = _lang.split('-')
  158. if len(_l) == 2:
  159. country = _l[1]
  160. else:
  161. country = _l[0].upper()
  162. if country == 'EN':
  163. country = 'US'
  164. ret_val['country'] = country
  165. # subdomain ...
  166. ret_val['subdomain'] = 'www.' + google_domains.get(country.upper(), 'google.com')
  167. # params & headers
  168. lang_country = '%s-%s' % (language, country) # (en-US, en-EN, de-DE, de-AU, fr-FR ..)
  169. # hl parameter:
  170. # https://developers.google.com/custom-search/docs/xml_results#hlsp The
  171. # Interface Language:
  172. # https://developers.google.com/custom-search/docs/xml_results_appendices#interfaceLanguages
  173. ret_val['params']['hl'] = lang_list.get(lang_country, language)
  174. # lr parameter:
  175. # The lr (language restrict) parameter restricts search results to
  176. # documents written in a particular language.
  177. # https://developers.google.com/custom-search/docs/xml_results#lrsp
  178. # Language Collection Values:
  179. # https://developers.google.com/custom-search/docs/xml_results_appendices#languageCollections
  180. if _any_language and supported_any_language:
  181. # interpretation is left up to Google (based on whoogle)
  182. #
  183. # - add parameter ``source=lnt``
  184. # - don't use parameter ``lr``
  185. # - don't add a ``Accept-Language`` HTTP header.
  186. ret_val['params']['source'] = 'lnt'
  187. else:
  188. # restricts search results to documents written in a particular
  189. # language.
  190. ret_val['params']['lr'] = "lang_" + lang_list.get(lang_country, language)
  191. return ret_val
  192. def detect_google_sorry(resp):
  193. if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
  194. raise SearxEngineCaptchaException()
  195. def request(query, params):
  196. """Google search request"""
  197. offset = (params['pageno'] - 1) * 10
  198. lang_info = get_lang_info(params, supported_languages, language_aliases, True)
  199. additional_parameters = {}
  200. if use_mobile_ui:
  201. additional_parameters = {
  202. 'asearch': 'arc',
  203. 'async': 'use_ac:true,_fmt:html',
  204. }
  205. # https://www.google.de/search?q=corona&hl=de&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  206. query_url = (
  207. 'https://'
  208. + lang_info['subdomain']
  209. + '/search'
  210. + "?"
  211. + urlencode(
  212. {
  213. 'q': query,
  214. **lang_info['params'],
  215. 'ie': "utf8",
  216. 'oe': "utf8",
  217. 'start': offset,
  218. 'filter': '0',
  219. **additional_parameters,
  220. }
  221. )
  222. )
  223. if params['time_range'] in time_range_dict:
  224. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  225. if params['safesearch']:
  226. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  227. params['url'] = query_url
  228. params['cookies']['CONSENT'] = "YES+"
  229. params['headers'].update(lang_info['headers'])
  230. if use_mobile_ui:
  231. params['headers']['Accept'] = '*/*'
  232. else:
  233. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  234. return params
  235. def response(resp):
  236. """Get response from google's search request"""
  237. detect_google_sorry(resp)
  238. results = []
  239. # convert the text to dom
  240. dom = html.fromstring(resp.text)
  241. # results --> answer
  242. answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
  243. if answer_list:
  244. answer_list = [_.xpath("normalize-space()") for _ in answer_list]
  245. results.append({'answer': ' '.join(answer_list)})
  246. else:
  247. logger.debug("did not find 'answer'")
  248. # results --> number_of_results
  249. if not use_mobile_ui:
  250. try:
  251. _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
  252. _digit = ''.join([n for n in _txt if n.isdigit()])
  253. number_of_results = int(_digit)
  254. results.append({'number_of_results': number_of_results})
  255. except Exception as e: # pylint: disable=broad-except
  256. logger.debug("did not 'number_of_results'")
  257. logger.error(e, exc_info=True)
  258. # parse results
  259. for result in eval_xpath_list(dom, results_xpath):
  260. # google *sections*
  261. if extract_text(eval_xpath(result, g_section_with_header)):
  262. logger.debug("ignoring <g-section-with-header>")
  263. continue
  264. try:
  265. title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
  266. if title_tag is None:
  267. # this not one of the common google results *section*
  268. logger.debug('ignoring item from the result_xpath list: missing title')
  269. continue
  270. title = extract_text(title_tag)
  271. url = eval_xpath_getindex(result, href_xpath, 0, None)
  272. if url is None:
  273. continue
  274. content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
  275. if content is None:
  276. logger.debug('ignoring item from the result_xpath list: missing content of title "%s"', title)
  277. continue
  278. logger.debug('add link to results: %s', title)
  279. results.append({'url': url, 'title': title, 'content': content})
  280. except Exception as e: # pylint: disable=broad-except
  281. logger.error(e, exc_info=True)
  282. continue
  283. # parse suggestion
  284. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  285. # append suggestion
  286. results.append({'suggestion': extract_text(suggestion)})
  287. # return results
  288. return results
  289. # get supported languages from their site
  290. def _fetch_supported_languages(resp):
  291. ret_val = {}
  292. dom = html.fromstring(resp.text)
  293. radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
  294. for x in radio_buttons:
  295. name = x.get("data-name")
  296. code = x.get("value").split('_')[-1]
  297. ret_val[code] = {"name": name}
  298. return ret_val