google.py 13 KB

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