google.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Google (Web)
  3. For detailed description of the *REST-full* API see: `Query Parameter
  4. Definitions`_.
  5. .. _Query Parameter Definitions:
  6. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  7. """
  8. # pylint: disable=invalid-name, missing-function-docstring, too-many-branches
  9. from urllib.parse import urlencode, urlparse
  10. from random import random
  11. from lxml import html
  12. from searx import logger
  13. from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
  14. from searx.exceptions import SearxEngineCaptchaException
  15. logger = logger.getChild('google engine')
  16. # about
  17. about = {
  18. "website": 'https://www.google.com',
  19. "wikidata_id": 'Q9366',
  20. "official_api_documentation": 'https://developers.google.com/custom-search/',
  21. "use_official_api": False,
  22. "require_api_key": False,
  23. "results": 'HTML',
  24. }
  25. # engine dependent config
  26. categories = ['general']
  27. paging = True
  28. time_range_support = True
  29. safesearch = True
  30. use_mobile_ui = False
  31. supported_languages_url = 'https://www.google.com/preferences?#languages'
  32. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  33. google_domains = {
  34. 'BG': 'google.bg', # Bulgaria
  35. 'CZ': 'google.cz', # Czech Republic
  36. 'DE': 'google.de', # Germany
  37. 'DK': 'google.dk', # Denmark
  38. 'AT': 'google.at', # Austria
  39. 'CH': 'google.ch', # Switzerland
  40. 'GR': 'google.gr', # Greece
  41. 'AU': 'google.com.au', # Australia
  42. 'CA': 'google.ca', # Canada
  43. 'GB': 'google.co.uk', # United Kingdom
  44. 'ID': 'google.co.id', # Indonesia
  45. 'IE': 'google.ie', # Ireland
  46. 'IN': 'google.co.in', # India
  47. 'MY': 'google.com.my', # Malaysia
  48. 'NZ': 'google.co.nz', # New Zealand
  49. 'PH': 'google.com.ph', # Philippines
  50. 'SG': 'google.com.sg', # Singapore
  51. 'US': 'google.com', # United States (google.us) redirects to .com
  52. 'ZA': 'google.co.za', # South Africa
  53. 'AR': 'google.com.ar', # Argentina
  54. 'CL': 'google.cl', # Chile
  55. 'ES': 'google.es', # Spain
  56. 'MX': 'google.com.mx', # Mexico
  57. 'EE': 'google.ee', # Estonia
  58. 'FI': 'google.fi', # Finland
  59. 'BE': 'google.be', # Belgium
  60. 'FR': 'google.fr', # France
  61. 'IL': 'google.co.il', # Israel
  62. 'HR': 'google.hr', # Croatia
  63. 'HU': 'google.hu', # Hungary
  64. 'IT': 'google.it', # Italy
  65. 'JP': 'google.co.jp', # Japan
  66. 'KR': 'google.co.kr', # South Korea
  67. 'LT': 'google.lt', # Lithuania
  68. 'LV': 'google.lv', # Latvia
  69. 'NO': 'google.no', # Norway
  70. 'NL': 'google.nl', # Netherlands
  71. 'PL': 'google.pl', # Poland
  72. 'BR': 'google.com.br', # Brazil
  73. 'PT': 'google.pt', # Portugal
  74. 'RO': 'google.ro', # Romania
  75. 'RU': 'google.ru', # Russia
  76. 'SK': 'google.sk', # Slovakia
  77. 'SI': 'google.si', # Slovenia
  78. 'SE': 'google.se', # Sweden
  79. 'TH': 'google.co.th', # Thailand
  80. 'TR': 'google.com.tr', # Turkey
  81. 'UA': 'google.com.ua', # Ukraine
  82. 'CN': 'google.com.hk', # There is no google.cn, we use .com.hk for zh-CN
  83. 'HK': 'google.com.hk', # Hong Kong
  84. 'TW': 'google.com.tw' # Taiwan
  85. }
  86. time_range_dict = {
  87. 'day': 'd',
  88. 'week': 'w',
  89. 'month': 'm',
  90. 'year': 'y'
  91. }
  92. # Filter results. 0: None, 1: Moderate, 2: Strict
  93. filter_mapping = {
  94. 0: 'off',
  95. 1: 'medium',
  96. 2: 'high'
  97. }
  98. # specific xpath variables
  99. # ------------------------
  100. results_xpath = '//div[contains(@class, "MjjYud")]'
  101. title_xpath = './/h3[1]'
  102. href_xpath = './/a/@href'
  103. content_xpath = './/div[@data-sncf]'
  104. results_xpath_mobile_ui = '//div[contains(@class, "g ")]'
  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, "card-section")]//a'
  110. # Since google does *auto-correction* on the first query these are not really
  111. # *spelling suggestions*, we use them anyway.
  112. spelling_suggestion_xpath = '//div[@class="med"]/p/a'
  113. def get_lang_info(params, lang_list, custom_aliases, supported_any_language):
  114. ret_val = {}
  115. _lang = params['language']
  116. _any_language = _lang.lower() == 'all'
  117. if _any_language:
  118. _lang = 'en-US'
  119. language = match_language(_lang, lang_list, custom_aliases)
  120. ret_val['language'] = language
  121. # the requested language from params (en, en-US, de, de-AT, fr, fr-CA, ...)
  122. _l = _lang.split('-')
  123. # the country code (US, AT, CA)
  124. if len(_l) == 2:
  125. country = _l[1]
  126. else:
  127. country = _l[0].upper()
  128. if country == 'EN':
  129. country = 'US'
  130. ret_val['country'] = country
  131. # the combination (en-US, en-EN, de-DE, de-AU, fr-FR, fr-FR)
  132. lang_country = '%s-%s' % (language, country)
  133. # subdomain
  134. ret_val['subdomain'] = 'www.' + google_domains.get(country.upper(), 'google.com')
  135. ret_val['params'] = {}
  136. ret_val['headers'] = {}
  137. if _any_language and supported_any_language:
  138. # based on whoogle
  139. ret_val['params']['source'] = 'lnt'
  140. else:
  141. # Accept-Language: fr-CH, fr;q=0.8, en;q=0.6, *;q=0.5
  142. ret_val['headers']['Accept-Language'] = ','.join([
  143. lang_country,
  144. language + ';q=0.8,',
  145. 'en;q=0.6',
  146. '*;q=0.5',
  147. ])
  148. # lr parameter:
  149. # https://developers.google.com/custom-search/docs/xml_results#lrsp
  150. # Language Collection Values:
  151. # https://developers.google.com/custom-search/docs/xml_results_appendices#languageCollections
  152. ret_val['params']['lr'] = "lang_" + lang_country if lang_country in lang_list else language
  153. ret_val['params']['hl'] = lang_country if lang_country in lang_list else language
  154. # hl parameter:
  155. # https://developers.google.com/custom-search/docs/xml_results#hlsp The
  156. # Interface Language:
  157. # https://developers.google.com/custom-search/docs/xml_results_appendices#interfaceLanguages
  158. return ret_val
  159. def detect_google_sorry(resp):
  160. resp_url = urlparse(resp.url)
  161. if resp_url.netloc == 'sorry.google.com' or resp_url.path.startswith('/sorry'):
  162. raise SearxEngineCaptchaException()
  163. def request(query, params):
  164. """Google search request"""
  165. offset = (params['pageno'] - 1) * 10
  166. lang_info = get_lang_info(
  167. # pylint: disable=undefined-variable
  168. params, supported_languages, language_aliases, True
  169. )
  170. additional_parameters = {}
  171. if use_mobile_ui:
  172. additional_parameters = {
  173. 'asearch': 'arc',
  174. 'async': 'use_ac:true,_fmt:html',
  175. }
  176. # https://www.google.de/search?q=corona&hl=de&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  177. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  178. 'q': query,
  179. **lang_info['params'],
  180. 'ie': "utf8",
  181. 'oe': "utf8",
  182. 'start': offset,
  183. 'filter': '0',
  184. 'ucbcb': 1,
  185. **additional_parameters,
  186. })
  187. if params['time_range'] in time_range_dict:
  188. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  189. if params['safesearch']:
  190. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  191. logger.debug("query_url --> %s", query_url)
  192. params['url'] = query_url
  193. logger.debug("HTTP header Accept-Language --> %s", lang_info.get('Accept-Language'))
  194. params['cookies']['CONSENT'] = "PENDING+" + str(random()*100)
  195. params['headers'].update(lang_info['headers'])
  196. if use_mobile_ui:
  197. params['headers']['Accept'] = '*/*'
  198. else:
  199. params['headers']['Accept'] = (
  200. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  201. )
  202. return params
  203. def response(resp):
  204. """Get response from google's search request"""
  205. detect_google_sorry(resp)
  206. results = []
  207. # convert the text to dom
  208. dom = html.fromstring(resp.text)
  209. # results --> answer
  210. answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
  211. if answer_list:
  212. answer_list = [_.xpath("normalize-space()") for _ in answer_list]
  213. results.append({'answer': ' '.join(answer_list)})
  214. else:
  215. logger.debug("did not find 'answer'")
  216. # results --> number_of_results
  217. if not use_mobile_ui:
  218. try:
  219. _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
  220. _digit = ''.join([n for n in _txt if n.isdigit()])
  221. number_of_results = int(_digit)
  222. results.append({'number_of_results': number_of_results})
  223. except Exception as e: # pylint: disable=broad-except
  224. logger.debug("did not 'number_of_results'")
  225. logger.error(e, exc_info=True)
  226. # parse results
  227. _results_xpath = results_xpath
  228. if use_mobile_ui:
  229. _results_xpath = results_xpath_mobile_ui
  230. for result in eval_xpath_list(dom, _results_xpath):
  231. # google *sections*
  232. if extract_text(eval_xpath(result, g_section_with_header)):
  233. logger.debug("ignoring <g-section-with-header>")
  234. continue
  235. try:
  236. title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
  237. if title_tag is None:
  238. # this not one of the common google results *section*
  239. logger.debug('ingoring item from the result_xpath list: missing title')
  240. continue
  241. title = extract_text(title_tag)
  242. url = eval_xpath_getindex(result, href_xpath, 0, None)
  243. if url is None:
  244. continue
  245. content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
  246. if content is None:
  247. logger.debug('ingoring item from the result_xpath list: missing content of title "%s"', title)
  248. continue
  249. logger.debug('add link to results: %s', title)
  250. results.append({
  251. 'url': url,
  252. 'title': title,
  253. 'content': content
  254. })
  255. except Exception as e: # pylint: disable=broad-except
  256. logger.error(e, exc_info=True)
  257. continue
  258. # parse suggestion
  259. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  260. # append suggestion
  261. results.append({'suggestion': extract_text(suggestion)})
  262. for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
  263. results.append({'correction': extract_text(correction)})
  264. # return results
  265. return results
  266. # get supported languages from their site
  267. def _fetch_supported_languages(resp):
  268. ret_val = {}
  269. dom = html.fromstring(resp.text)
  270. radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
  271. for x in radio_buttons:
  272. name = x.get("data-name")
  273. code = x.get("value").split('_')[-1]
  274. ret_val[code] = {"name": name}
  275. return ret_val