google.py 13 KB

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