google.py 11 KB

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