google.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Google (Web)
  3. :website: https://www.google.com
  4. :provide-api: yes (https://developers.google.com/custom-search/)
  5. :using-api: not the offical, since it needs registration to another service
  6. :results: HTML
  7. :stable: no
  8. :parse: url, title, content, number_of_results, answer, suggestion, correction
  9. For detailed description of the *REST-full* API see: `Query Parameter
  10. Definitions`_.
  11. .. _Query Parameter Definitions:
  12. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  13. """
  14. # pylint: disable=invalid-name, missing-function-docstring
  15. from urllib.parse import urlencode, urlparse
  16. from lxml import html
  17. from searx import logger
  18. from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
  19. from searx.exceptions import SearxEngineCaptchaException
  20. logger = logger.getChild('google engine')
  21. # engine dependent config
  22. categories = ['general']
  23. paging = True
  24. language_support = True
  25. time_range_support = True
  26. safesearch = True
  27. supported_languages_url = 'https://www.google.com/preferences?#languages'
  28. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  29. google_domains = {
  30. 'BG': 'google.bg', # Bulgaria
  31. 'CZ': 'google.cz', # Czech Republic
  32. 'DE': 'google.de', # Germany
  33. 'DK': 'google.dk', # Denmark
  34. 'AT': 'google.at', # Austria
  35. 'CH': 'google.ch', # Switzerland
  36. 'GR': 'google.gr', # Greece
  37. 'AU': 'google.com.au', # Australia
  38. 'CA': 'google.ca', # Canada
  39. 'GB': 'google.co.uk', # United Kingdom
  40. 'ID': 'google.co.id', # Indonesia
  41. 'IE': 'google.ie', # Ireland
  42. 'IN': 'google.co.in', # India
  43. 'MY': 'google.com.my', # Malaysia
  44. 'NZ': 'google.co.nz', # New Zealand
  45. 'PH': 'google.com.ph', # Philippines
  46. 'SG': 'google.com.sg', # Singapore
  47. # 'US': 'google.us', # United States, redirect to .com
  48. 'ZA': 'google.co.za', # South Africa
  49. 'AR': 'google.com.ar', # Argentina
  50. 'CL': 'google.cl', # Chile
  51. 'ES': 'google.es', # Spain
  52. 'MX': 'google.com.mx', # Mexico
  53. 'EE': 'google.ee', # Estonia
  54. 'FI': 'google.fi', # Finland
  55. 'BE': 'google.be', # Belgium
  56. 'FR': 'google.fr', # France
  57. 'IL': 'google.co.il', # Israel
  58. 'HR': 'google.hr', # Croatia
  59. 'HU': 'google.hu', # Hungary
  60. 'IT': 'google.it', # Italy
  61. 'JP': 'google.co.jp', # Japan
  62. 'KR': 'google.co.kr', # South Korea
  63. 'LT': 'google.lt', # Lithuania
  64. 'LV': 'google.lv', # Latvia
  65. 'NO': 'google.no', # Norway
  66. 'NL': 'google.nl', # Netherlands
  67. 'PL': 'google.pl', # Poland
  68. 'BR': 'google.com.br', # Brazil
  69. 'PT': 'google.pt', # Portugal
  70. 'RO': 'google.ro', # Romania
  71. 'RU': 'google.ru', # Russia
  72. 'SK': 'google.sk', # Slovakia
  73. 'SI': 'google.si', # Slovenia
  74. 'SE': 'google.se', # Sweden
  75. 'TH': 'google.co.th', # Thailand
  76. 'TR': 'google.com.tr', # Turkey
  77. 'UA': 'google.com.ua', # Ukraine
  78. # 'CN': 'google.cn', # China, only from China ?
  79. 'HK': 'google.com.hk', # Hong Kong
  80. 'TW': 'google.com.tw' # Taiwan
  81. }
  82. time_range_dict = {
  83. 'day': 'd',
  84. 'week': 'w',
  85. 'month': 'm',
  86. 'year': 'y'
  87. }
  88. # Filter results. 0: None, 1: Moderate, 2: Strict
  89. filter_mapping = {
  90. 0: 'off',
  91. 1: 'medium',
  92. 2: 'high'
  93. }
  94. # specific xpath variables
  95. # ------------------------
  96. # google results are grouped into <div class="g" ../>
  97. results_xpath = '//div[@class="g"]'
  98. # google *sections* are no usual *results*, we ignore them
  99. g_section_with_header = './g-section-with-header'
  100. # the title is a h3 tag relative to the result group
  101. title_xpath = './/h3[1]'
  102. # in the result group there is <div class="yuRUbf" ../> it's first child is a <a
  103. # href=...>
  104. href_xpath = './/div[@class="yuRUbf"]//a/@href'
  105. # in the result group there is <div class="IsZvec" ../> containing he *content*
  106. content_xpath = './/div[@class="IsZvec"]'
  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_country(params, lang_list, custom_aliases):
  114. """Returns a tuple with *langauage* on its first and *country* on its second
  115. position."""
  116. language = params['language']
  117. if language == 'all':
  118. language = 'en-US'
  119. language_array = language.split('-')
  120. if len(language_array) == 2:
  121. country = language_array[1]
  122. else:
  123. country = language_array[0].upper()
  124. language = match_language(language, lang_list, custom_aliases)
  125. lang_country = '%s-%s' % (language, country)
  126. if lang_country == 'en-EN':
  127. lang_country = 'en'
  128. return language, country, lang_country
  129. def request(query, params):
  130. """Google search request"""
  131. offset = (params['pageno'] - 1) * 10
  132. language, country, lang_country = get_lang_country(
  133. # pylint: disable=undefined-variable
  134. params, supported_languages, language_aliases
  135. )
  136. subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
  137. # https://www.google.de/search?q=corona&hl=de-DE&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  138. query_url = 'https://' + subdomain + '/search' + "?" + urlencode({
  139. 'q': query,
  140. 'hl': lang_country,
  141. 'lr': "lang_" + language,
  142. 'ie': "utf8",
  143. 'oe': "utf8",
  144. 'start': offset,
  145. })
  146. if params['time_range'] in time_range_dict:
  147. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  148. if params['safesearch']:
  149. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  150. params['url'] = query_url
  151. logger.debug("query_url --> %s", query_url)
  152. # en-US,en;q=0.8,en;q=0.5
  153. params['headers']['Accept-Language'] = (
  154. lang_country + ',' + language + ';q=0.8,' + language + ';q=0.5'
  155. )
  156. logger.debug("HTTP header Accept-Language --> %s",
  157. params['headers']['Accept-Language'])
  158. params['headers']['Accept'] = (
  159. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  160. )
  161. # params['google_subdomain'] = subdomain
  162. return params
  163. def response(resp):
  164. """Get response from google's search request"""
  165. results = []
  166. # detect google sorry
  167. resp_url = urlparse(resp.url)
  168. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  169. raise SearxEngineCaptchaException()
  170. if resp_url.path.startswith('/sorry'):
  171. raise SearxEngineCaptchaException()
  172. # which subdomain ?
  173. # subdomain = resp.search_params.get('google_subdomain')
  174. # convert the text to dom
  175. dom = html.fromstring(resp.text)
  176. # results --> answer
  177. answer = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]//text()')
  178. if answer:
  179. results.append({'answer': ' '.join(answer)})
  180. else:
  181. logger.debug("did not found 'answer'")
  182. # results --> number_of_results
  183. try:
  184. _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
  185. _digit = ''.join([n for n in _txt if n.isdigit()])
  186. number_of_results = int(_digit)
  187. results.append({'number_of_results': number_of_results})
  188. except Exception as e: # pylint: disable=broad-except
  189. logger.debug("did not 'number_of_results'")
  190. logger.error(e, exc_info=True)
  191. # parse results
  192. for result in eval_xpath_list(dom, results_xpath):
  193. # google *sections*
  194. if extract_text(eval_xpath(result, g_section_with_header)):
  195. logger.debug("ingoring <g-section-with-header>")
  196. continue
  197. try:
  198. title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
  199. if title_tag is None:
  200. # this not one of the common google results *section*
  201. logger.debug('ingoring <div class="g" ../> section: missing title')
  202. continue
  203. title = extract_text(title_tag)
  204. url = eval_xpath_getindex(result, href_xpath, 0)
  205. content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
  206. results.append({
  207. 'url': url,
  208. 'title': title,
  209. 'content': content
  210. })
  211. except Exception as e: # pylint: disable=broad-except
  212. logger.error(e, exc_info=True)
  213. # from lxml import etree
  214. # logger.debug(etree.tostring(result, pretty_print=True))
  215. # import pdb
  216. # pdb.set_trace()
  217. continue
  218. # parse suggestion
  219. for suggestion in eval_xpath_list(dom, suggestion_xpath):
  220. # append suggestion
  221. results.append({'suggestion': extract_text(suggestion)})
  222. for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
  223. results.append({'correction': extract_text(correction)})
  224. # return results
  225. return results
  226. # get supported languages from their site
  227. def _fetch_supported_languages(resp):
  228. ret_val = {}
  229. dom = html.fromstring(resp.text)
  230. radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
  231. for x in radio_buttons:
  232. name = x.get("data-name")
  233. code = x.get("value").split('_')[-1]
  234. ret_val[code] = {"name": name}
  235. return ret_val