google.py 13 KB

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