google.py 13 KB

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