google.py 10 KB

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