google.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. import re
  11. from cgi import escape
  12. from urllib import urlencode
  13. from urlparse import urlparse, parse_qsl
  14. from lxml import html
  15. from searx.poolrequests import get
  16. from searx.engines.xpath import extract_text, extract_url
  17. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. language_support = True
  21. use_locale_domain = True
  22. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  23. default_hostname = 'www.google.com'
  24. country_to_hostname = {
  25. 'BG': 'www.google.bg', # Bulgaria
  26. 'CZ': 'www.google.cz', # Czech Republic
  27. 'DE': 'www.google.de', # Germany
  28. 'DK': 'www.google.dk', # Denmark
  29. 'AT': 'www.google.at', # Austria
  30. 'CH': 'www.google.ch', # Switzerland
  31. 'GR': 'www.google.gr', # Greece
  32. 'AU': 'www.google.com.au', # Australia
  33. 'CA': 'www.google.ca', # Canada
  34. 'GB': 'www.google.co.uk', # United Kingdom
  35. 'ID': 'www.google.co.id', # Indonesia
  36. 'IE': 'www.google.ie', # Ireland
  37. 'IN': 'www.google.co.in', # India
  38. 'MY': 'www.google.com.my', # Malaysia
  39. 'NZ': 'www.google.co.nz', # New Zealand
  40. 'PH': 'www.google.com.ph', # Philippines
  41. 'SG': 'www.google.com.sg', # Singapore
  42. # 'US': 'www.google.us', # United State, redirect to .com
  43. 'ZA': 'www.google.co.za', # South Africa
  44. 'AR': 'www.google.com.ar', # Argentina
  45. 'CL': 'www.google.cl', # Chile
  46. 'ES': 'www.google.es', # Span
  47. 'MX': 'www.google.com.mx', # Mexico
  48. 'EE': 'www.google.ee', # Estonia
  49. 'FI': 'www.google.fi', # Finland
  50. 'BE': 'www.google.be', # Belgium
  51. 'FR': 'www.google.fr', # France
  52. 'IL': 'www.google.co.il', # Israel
  53. 'HR': 'www.google.hr', # Croatia
  54. 'HU': 'www.google.hu', # Hungary
  55. 'IT': 'www.google.it', # Italy
  56. 'JP': 'www.google.co.jp', # Japan
  57. 'KR': 'www.google.co.kr', # South Korean
  58. 'LT': 'www.google.lt', # Lithuania
  59. 'LV': 'www.google.lv', # Latvia
  60. 'NO': 'www.google.no', # Norway
  61. 'NL': 'www.google.nl', # Netherlands
  62. 'PL': 'www.google.pl', # Poland
  63. 'BR': 'www.google.com.br', # Brazil
  64. 'PT': 'www.google.pt', # Portugal
  65. 'RO': 'www.google.ro', # Romania
  66. 'RU': 'www.google.ru', # Russia
  67. 'SK': 'www.google.sk', # Slovakia
  68. 'SL': 'www.google.si', # Slovenia (SL -> si)
  69. 'SE': 'www.google.se', # Sweden
  70. 'TH': 'www.google.co.th', # Thailand
  71. 'TR': 'www.google.com.tr', # Turkey
  72. 'UA': 'www.google.com.ua', # Ikraine
  73. # 'CN': 'www.google.cn', # China, only from china ?
  74. 'HK': 'www.google.com.hk', # Hong kong
  75. 'TW': 'www.google.com.tw' # Taiwan
  76. }
  77. # osm
  78. url_map = 'https://www.openstreetmap.org/'\
  79. + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
  80. # search-url
  81. search_path = '/search'
  82. search_url = ('https://{hostname}' +
  83. search_path +
  84. '?{query}&start={offset}&gbv=1')
  85. # other URLs
  86. map_hostname_start = 'maps.google.'
  87. maps_path = '/maps'
  88. redirect_path = '/url'
  89. images_path = '/images'
  90. # specific xpath variables
  91. results_xpath = '//li[@class="g"]'
  92. url_xpath = './/h3/a/@href'
  93. title_xpath = './/h3'
  94. content_xpath = './/span[@class="st"]'
  95. content_misc_xpath = './/div[@class="f slp"]'
  96. suggestion_xpath = '//p[@class="_Bmc"]'
  97. # map : detail location
  98. map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'
  99. map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'
  100. map_website_url_xpath = 'h3[2]/a/@href'
  101. map_website_title_xpath = 'h3[2]'
  102. # map : near the location
  103. map_near = 'table[@class="ts"]//tr'
  104. map_near_title = './/h4'
  105. map_near_url = './/h4/a/@href'
  106. map_near_phone = './/span[@class="nobr"]'
  107. # images
  108. images_xpath = './/div/a'
  109. image_url_xpath = './@href'
  110. image_img_src_xpath = './img/@src'
  111. # property names
  112. # FIXME : no translation
  113. property_address = "Address"
  114. property_phone = "Phone number"
  115. # cookies
  116. pref_cookie = ''
  117. nid_cookie = {}
  118. # see https://support.google.com/websearch/answer/873?hl=en
  119. def get_google_pref_cookie():
  120. global pref_cookie
  121. if pref_cookie == '':
  122. resp = get('https://www.google.com/ncr', allow_redirects=False)
  123. pref_cookie = resp.cookies["PREF"]
  124. return pref_cookie
  125. def get_google_nid_cookie(google_hostname):
  126. global nid_cookie
  127. if google_hostname not in nid_cookie:
  128. resp = get('https://' + google_hostname)
  129. nid_cookie[google_hostname] = resp.cookies.get("NID", None)
  130. return nid_cookie[google_hostname]
  131. # remove google-specific tracking-url
  132. def parse_url(url_string, google_hostname):
  133. # sanity check
  134. if url_string is None:
  135. return url_string
  136. # normal case
  137. parsed_url = urlparse(url_string)
  138. if (parsed_url.netloc in [google_hostname, '']
  139. and parsed_url.path == redirect_path):
  140. query = dict(parse_qsl(parsed_url.query))
  141. return query['q']
  142. else:
  143. return url_string
  144. # returns extract_text on the first result selected by the xpath or None
  145. def extract_text_from_dom(result, xpath):
  146. r = result.xpath(xpath)
  147. if len(r) > 0:
  148. return escape(extract_text(r[0]))
  149. return None
  150. # do search-request
  151. def request(query, params):
  152. offset = (params['pageno'] - 1) * 10
  153. if params['language'] == 'all':
  154. language = 'en'
  155. country = 'US'
  156. else:
  157. language_array = params['language'].lower().split('_')
  158. if len(language_array) == 2:
  159. country = language_array[1]
  160. else:
  161. country = 'US'
  162. language = language_array[0] + ',' + language_array[0] + '-' + country
  163. if use_locale_domain:
  164. google_hostname = country_to_hostname.get(country.upper(), default_hostname)
  165. else:
  166. google_hostname = default_hostname
  167. params['url'] = search_url.format(offset=offset,
  168. query=urlencode({'q': query}),
  169. hostname=google_hostname)
  170. params['headers']['Accept-Language'] = language
  171. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  172. if google_hostname == default_hostname:
  173. params['cookies']['PREF'] = get_google_pref_cookie()
  174. params['cookies']['NID'] = get_google_nid_cookie(google_hostname)
  175. params['google_hostname'] = google_hostname
  176. return params
  177. # get response from search-request
  178. def response(resp):
  179. results = []
  180. # detect google sorry
  181. resp_url = urlparse(resp.url)
  182. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  183. raise RuntimeWarning('sorry.google.com')
  184. # which hostname ?
  185. google_hostname = resp.search_params.get('google_hostname')
  186. google_url = "https://" + google_hostname
  187. # convert the text to dom
  188. dom = html.fromstring(resp.text)
  189. # parse results
  190. for result in dom.xpath(results_xpath):
  191. title = extract_text(result.xpath(title_xpath)[0])
  192. try:
  193. url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname)
  194. parsed_url = urlparse(url, google_hostname)
  195. # map result
  196. if ((parsed_url.netloc == google_hostname and parsed_url.path.startswith(maps_path))
  197. or (parsed_url.netloc.startswith(map_hostname_start))):
  198. x = result.xpath(map_near)
  199. if len(x) > 0:
  200. # map : near the location
  201. results = results + parse_map_near(parsed_url, x, google_hostname)
  202. else:
  203. # map : detail about a location
  204. results = results + parse_map_detail(parsed_url, result, google_hostname)
  205. # google news
  206. elif (parsed_url.netloc == google_hostname
  207. and parsed_url.path == search_path):
  208. # skipping news results
  209. pass
  210. # images result
  211. elif (parsed_url.netloc == google_hostname
  212. and parsed_url.path == images_path):
  213. # only thumbnail image provided,
  214. # so skipping image results
  215. # results = results + parse_images(result, google_hostname)
  216. pass
  217. else:
  218. # normal result
  219. content = extract_text_from_dom(result, content_xpath)
  220. if content is None:
  221. continue
  222. content_misc = extract_text_from_dom(result, content_misc_xpath)
  223. if content_misc is not None:
  224. content = content_misc + "<br />" + content
  225. # append result
  226. results.append({'url': url,
  227. 'title': title,
  228. 'content': content
  229. })
  230. except:
  231. continue
  232. # parse suggestion
  233. for suggestion in dom.xpath(suggestion_xpath):
  234. # append suggestion
  235. results.append({'suggestion': escape(extract_text(suggestion))})
  236. # return results
  237. return results
  238. def parse_images(result, google_hostname):
  239. results = []
  240. for image in result.xpath(images_xpath):
  241. url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname)
  242. img_src = extract_text(image.xpath(image_img_src_xpath)[0])
  243. # append result
  244. results.append({'url': url,
  245. 'title': '',
  246. 'content': '',
  247. 'img_src': img_src,
  248. 'template': 'images.html'
  249. })
  250. return results
  251. def parse_map_near(parsed_url, x, google_hostname):
  252. results = []
  253. for result in x:
  254. title = extract_text_from_dom(result, map_near_title)
  255. url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname)
  256. attributes = []
  257. phone = extract_text_from_dom(result, map_near_phone)
  258. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  259. results.append({'title': title,
  260. 'url': url,
  261. 'content': attributes_to_html(attributes)
  262. })
  263. return results
  264. def parse_map_detail(parsed_url, result, google_hostname):
  265. results = []
  266. # try to parse the geoloc
  267. m = re.search('@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path)
  268. if m is None:
  269. m = re.search('ll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query)
  270. if m is not None:
  271. # geoloc found (ignored)
  272. lon = float(m.group(2)) # noqa
  273. lat = float(m.group(1)) # noqa
  274. zoom = int(m.group(3)) # noqa
  275. # attributes
  276. attributes = []
  277. address = extract_text_from_dom(result, map_address_xpath)
  278. phone = extract_text_from_dom(result, map_phone_xpath)
  279. add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon))
  280. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  281. # title / content / url
  282. website_title = extract_text_from_dom(result, map_website_title_xpath)
  283. content = extract_text_from_dom(result, content_xpath)
  284. website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname)
  285. # add a result if there is a website
  286. if website_url is not None:
  287. results.append({'title': website_title,
  288. 'content': (content + '<br />' if content is not None else '')
  289. + attributes_to_html(attributes),
  290. 'url': website_url
  291. })
  292. return results
  293. def add_attributes(attributes, name, value, url):
  294. if value is not None and len(value) > 0:
  295. attributes.append({'label': name, 'value': value, 'url': url})
  296. def attributes_to_html(attributes):
  297. retval = '<table class="table table-striped">'
  298. for a in attributes:
  299. value = a.get('value')
  300. if 'url' in a:
  301. value = '<a href="' + a.get('url') + '">' + value + '</a>'
  302. retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>'
  303. retval = retval + '</table>'
  304. return retval