google.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # Google (Web)
  2. #
  3. # @website https://www.google.com
  4. # @provide-api yes (https://developers.google.com/custom-search/)
  5. #
  6. # @using-api no
  7. # @results HTML
  8. # @stable no (HTML can change)
  9. # @parse url, title, content, suggestion
  10. from urllib import urlencode
  11. from urlparse import urlparse, parse_qsl
  12. from lxml import html
  13. from searx.poolrequests import get
  14. from searx.engines.xpath import extract_text, extract_url
  15. # engine dependent config
  16. categories = ['general']
  17. paging = True
  18. language_support = True
  19. use_locale_domain = True
  20. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  21. default_hostname = 'www.google.com'
  22. country_to_hostname = {
  23. 'BG': 'www.google.bg', # Bulgaria
  24. 'CZ': 'www.google.cz', # Czech Republic
  25. 'DE': 'www.google.de', # Germany
  26. 'DK': 'www.google.dk', # Denmark
  27. 'AT': 'www.google.at', # Austria
  28. 'CH': 'www.google.ch', # Switzerland
  29. 'GR': 'www.google.gr', # Greece
  30. 'AU': 'www.google.com.au', # Australia
  31. 'CA': 'www.google.ca', # Canada
  32. 'GB': 'www.google.co.uk', # United Kingdom
  33. 'ID': 'www.google.co.id', # Indonesia
  34. 'IE': 'www.google.ie', # Ireland
  35. 'IN': 'www.google.co.in', # India
  36. 'MY': 'www.google.com.my', # Malaysia
  37. 'NZ': 'www.google.co.nz', # New Zealand
  38. 'PH': 'www.google.com.ph', # Philippines
  39. 'SG': 'www.google.com.sg', # Singapore
  40. # 'US': 'www.google.us', # United State, redirect to .com
  41. 'ZA': 'www.google.co.za', # South Africa
  42. 'AR': 'www.google.com.ar', # Argentina
  43. 'CL': 'www.google.cl', # Chile
  44. 'ES': 'www.google.es', # Span
  45. 'MX': 'www.google.com.mx', # Mexico
  46. 'EE': 'www.google.ee', # Estonia
  47. 'FI': 'www.google.fi', # Finland
  48. 'BE': 'www.google.be', # Belgium
  49. 'FR': 'www.google.fr', # France
  50. 'IL': 'www.google.co.il', # Israel
  51. 'HR': 'www.google.hr', # Croatia
  52. 'HU': 'www.google.hu', # Hungary
  53. 'IT': 'www.google.it', # Italy
  54. 'JP': 'www.google.co.jp', # Japan
  55. 'KR': 'www.google.co.kr', # South Korean
  56. 'LT': 'www.google.lt', # Lithuania
  57. 'LV': 'www.google.lv', # Latvia
  58. 'NO': 'www.google.no', # Norway
  59. 'NL': 'www.google.nl', # Netherlands
  60. 'PL': 'www.google.pl', # Poland
  61. 'BR': 'www.google.com.br', # Brazil
  62. 'PT': 'www.google.pt', # Portugal
  63. 'RO': 'www.google.ro', # Romania
  64. 'RU': 'www.google.ru', # Russia
  65. 'SK': 'www.google.sk', # Slovakia
  66. 'SL': 'www.google.si', # Slovenia (SL -> si)
  67. 'SE': 'www.google.se', # Sweden
  68. 'TH': 'www.google.co.th', # Thailand
  69. 'TR': 'www.google.com.tr', # Turkey
  70. 'UA': 'www.google.com.ua', # Ikraine
  71. # 'CN': 'www.google.cn', # China, only from china ?
  72. 'HK': 'www.google.com.hk', # Hong kong
  73. 'TW': 'www.google.com.tw' # Taiwan
  74. }
  75. # search-url
  76. search_path = '/search'
  77. maps_path = '/maps/'
  78. redirect_path = '/url'
  79. images_path = '/images'
  80. search_url = ('https://{hostname}' +
  81. search_path +
  82. '?{query}&start={offset}&gbv=1')
  83. # specific xpath variables
  84. results_xpath = '//li[@class="g"]'
  85. url_xpath = './/h3/a/@href'
  86. title_xpath = './/h3'
  87. content_xpath = './/span[@class="st"]'
  88. content_misc_xpath = './/div[@class="f slp"]'
  89. suggestion_xpath = '//p[@class="_Bmc"]'
  90. images_xpath = './/div/a'
  91. image_url_xpath = './@href'
  92. image_img_src_xpath = './img/@src'
  93. pref_cookie = ''
  94. nid_cookie = {}
  95. # see https://support.google.com/websearch/answer/873?hl=en
  96. def get_google_pref_cookie():
  97. global pref_cookie
  98. if pref_cookie == '':
  99. resp = get('https://www.google.com/ncr', allow_redirects=False)
  100. pref_cookie = resp.cookies["PREF"]
  101. return pref_cookie
  102. def get_google_nid_cookie(google_hostname):
  103. global nid_cookie
  104. if google_hostname not in nid_cookie:
  105. resp = get('https://' + google_hostname)
  106. nid_cookie[google_hostname] = resp.cookies.get("NID", None)
  107. return nid_cookie[google_hostname]
  108. # remove google-specific tracking-url
  109. def parse_url(url_string, google_hostname):
  110. parsed_url = urlparse(url_string)
  111. if (parsed_url.netloc in [google_hostname, '']
  112. and parsed_url.path == redirect_path):
  113. query = dict(parse_qsl(parsed_url.query))
  114. return query['q']
  115. else:
  116. return url_string
  117. # returns extract_text on the first result selected by the xpath or None
  118. def extract_text_from_dom(result, xpath):
  119. r = result.xpath(xpath)
  120. if len(r) > 0:
  121. return extract_text(r[0])
  122. return None
  123. # do search-request
  124. def request(query, params):
  125. offset = (params['pageno'] - 1) * 10
  126. if params['language'] == 'all':
  127. language = 'en'
  128. country = 'US'
  129. else:
  130. language_array = params['language'].lower().split('_')
  131. if len(language_array) == 2:
  132. country = language_array[1]
  133. else:
  134. country = ' '
  135. language = language_array[0] + ',' + language_array[0] + '-' + country
  136. if use_locale_domain:
  137. google_hostname = country_to_hostname.get(country.upper(), default_hostname)
  138. else:
  139. google_hostname = default_hostname
  140. params['url'] = search_url.format(offset=offset,
  141. query=urlencode({'q': query}),
  142. hostname=google_hostname)
  143. params['headers']['Accept-Language'] = language
  144. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  145. if google_hostname == default_hostname:
  146. params['cookies']['PREF'] = get_google_pref_cookie()
  147. params['cookies']['NID'] = get_google_nid_cookie(google_hostname)
  148. params['google_hostname'] = google_hostname
  149. return params
  150. # get response from search-request
  151. def response(resp):
  152. results = []
  153. # detect google sorry
  154. resp_url = urlparse(resp.url)
  155. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  156. raise RuntimeWarning('sorry.google.com')
  157. # which hostname ?
  158. google_hostname = resp.search_params.get('google_hostname')
  159. google_url = "https://" + google_hostname
  160. # convert the text to dom
  161. dom = html.fromstring(resp.text)
  162. # parse results
  163. for result in dom.xpath(results_xpath):
  164. title = extract_text(result.xpath(title_xpath)[0])
  165. try:
  166. url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname)
  167. parsed_url = urlparse(url, google_hostname)
  168. if (parsed_url.netloc == google_hostname
  169. and (parsed_url.path == search_path
  170. or parsed_url.path.startswith(maps_path))):
  171. # remove the link to google news and google maps
  172. # FIXME : sometimes the URL is https://maps.google.*/maps
  173. # no consequence, the result trigger an exception after which is ignored
  174. continue
  175. # images result
  176. if (parsed_url.netloc == google_hostname
  177. and parsed_url.path == images_path):
  178. # only thumbnail image provided,
  179. # so skipping image results
  180. # results = results + parse_images(result, google_hostname)
  181. pass
  182. else:
  183. # normal result
  184. content = extract_text_from_dom(result, content_xpath)
  185. if content is None:
  186. continue
  187. content_misc = extract_text_from_dom(result, content_misc_xpath)
  188. if content_misc is not None:
  189. content = content_misc + "<br />" + content
  190. # append result
  191. results.append({'url': url,
  192. 'title': title,
  193. 'content': content})
  194. except Exception:
  195. continue
  196. # parse suggestion
  197. for suggestion in dom.xpath(suggestion_xpath):
  198. # append suggestion
  199. results.append({'suggestion': extract_text(suggestion)})
  200. # return results
  201. return results
  202. def parse_images(result, google_hostname):
  203. results = []
  204. for image in result.xpath(images_xpath):
  205. url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname)
  206. img_src = extract_text(image.xpath(image_img_src_xpath)[0])
  207. # append result
  208. results.append({'url': url,
  209. 'title': '',
  210. 'content': '',
  211. 'img_src': img_src,
  212. 'template': 'images.html'})
  213. return results