google.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 flask_babel import gettext
  18. from searx import logger
  19. from searx.utils import match_language, extract_text, eval_xpath
  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 extract_text_from_dom(result, xpath):
  114. """returns extract_text on the first result selected by the xpath or None"""
  115. r = eval_xpath(result, xpath)
  116. if len(r) > 0:
  117. return extract_text(r[0])
  118. return None
  119. def get_lang_country(params, lang_list, custom_aliases):
  120. """Returns a tuple with *langauage* on its first and *country* on its second
  121. position."""
  122. language = params['language']
  123. if language == 'all':
  124. language = 'en-US'
  125. language_array = language.split('-')
  126. if len(language_array) == 2:
  127. country = language_array[1]
  128. else:
  129. country = language_array[0].upper()
  130. language = match_language(language, lang_list, custom_aliases)
  131. lang_country = '%s-%s' % (language, country)
  132. if lang_country == 'en-EN':
  133. lang_country = 'en'
  134. return language, country, lang_country
  135. def request(query, params):
  136. """Google search request"""
  137. offset = (params['pageno'] - 1) * 10
  138. language, country, lang_country = get_lang_country(
  139. # pylint: disable=undefined-variable
  140. params, supported_languages, language_aliases
  141. )
  142. subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
  143. # https://www.google.de/search?q=corona&hl=de-DE&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
  144. query_url = 'https://' + subdomain + '/search' + "?" + urlencode({
  145. 'q': query,
  146. 'hl': lang_country,
  147. 'lr': "lang_" + language,
  148. 'ie': "utf8",
  149. 'oe': "utf8",
  150. 'start': offset,
  151. })
  152. if params['time_range'] in time_range_dict:
  153. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  154. if params['safesearch']:
  155. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  156. params['url'] = query_url
  157. logger.debug("query_url --> %s", query_url)
  158. # en-US,en;q=0.8,en;q=0.5
  159. params['headers']['Accept-Language'] = (
  160. lang_country + ',' + language + ';q=0.8,' + language + ';q=0.5'
  161. )
  162. logger.debug("HTTP header Accept-Language --> %s",
  163. params['headers']['Accept-Language'])
  164. params['headers']['Accept'] = (
  165. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  166. )
  167. # params['google_subdomain'] = subdomain
  168. return params
  169. def response(resp):
  170. """Get response from google's search request"""
  171. results = []
  172. # detect google sorry
  173. resp_url = urlparse(resp.url)
  174. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  175. raise RuntimeWarning('sorry.google.com')
  176. if resp_url.path.startswith('/sorry'):
  177. raise RuntimeWarning(gettext('CAPTCHA required'))
  178. # which subdomain ?
  179. # subdomain = resp.search_params.get('google_subdomain')
  180. # convert the text to dom
  181. dom = html.fromstring(resp.text)
  182. # results --> answer
  183. answer = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]//text()')
  184. if answer:
  185. results.append({'answer': ' '.join(answer)})
  186. else:
  187. logger.debug("did not found 'answer'")
  188. # results --> number_of_results
  189. try:
  190. _txt = eval_xpath(dom, '//div[@id="result-stats"]//text()')[0]
  191. _digit = ''.join([n for n in _txt if n.isdigit()])
  192. number_of_results = int(_digit)
  193. results.append({'number_of_results': number_of_results})
  194. except Exception as e: # pylint: disable=broad-except
  195. logger.debug("did not 'number_of_results'")
  196. logger.error(e, exc_info=True)
  197. # parse results
  198. for result in eval_xpath(dom, results_xpath):
  199. # google *sections*
  200. if extract_text(eval_xpath(result, g_section_with_header)):
  201. logger.debug("ingoring <g-section-with-header>")
  202. continue
  203. try:
  204. title_tag = eval_xpath(result, title_xpath)
  205. if not title_tag:
  206. # this not one of the common google results *section*
  207. logger.debug('ingoring <div class="g" ../> section: missing title')
  208. continue
  209. title = extract_text(title_tag[0])
  210. url = eval_xpath(result, href_xpath)[0]
  211. content = extract_text_from_dom(result, content_xpath)
  212. results.append({
  213. 'url': url,
  214. 'title': title,
  215. 'content': content
  216. })
  217. except Exception as e: # pylint: disable=broad-except
  218. logger.error(e, exc_info=True)
  219. # from lxml import etree
  220. # logger.debug(etree.tostring(result, pretty_print=True))
  221. # import pdb
  222. # pdb.set_trace()
  223. continue
  224. # parse suggestion
  225. for suggestion in eval_xpath(dom, suggestion_xpath):
  226. # append suggestion
  227. results.append({'suggestion': extract_text(suggestion)})
  228. for correction in eval_xpath(dom, spelling_suggestion_xpath):
  229. results.append({'correction': extract_text(correction)})
  230. # return results
  231. return results
  232. # get supported languages from their site
  233. def _fetch_supported_languages(resp):
  234. ret_val = {}
  235. dom = html.fromstring(resp.text)
  236. radio_buttons = eval_xpath(dom, '//*[@id="langSec"]//input[@name="lr"]')
  237. for x in radio_buttons:
  238. name = x.get("data-name")
  239. code = x.get("value").split('_')[-1]
  240. ret_val[code] = {"name": name}
  241. return ret_val