google.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 urllib import urlencode
  12. from urlparse import urlparse, parse_qsl
  13. from lxml import html, etree
  14. from searx.engines.xpath import extract_text, extract_url
  15. from searx.search import logger
  16. logger = logger.getChild('google engine')
  17. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. language_support = True
  21. use_locale_domain = True
  22. supported_languages = ["ach", "af", "ak", "az", "ms", "ban", "xx-bork", "bs", "br", "ca",
  23. "ceb", "ckb", "cs", "sn", "co", "cy", "da", "de", "yo", "et",
  24. "xx-elmer", "en", "es", "es-419", "eo", "eu", "ee", "tl", "fo", "fr",
  25. "gaa", "ga", "gd", "gl", "gn", "xx-hacker", "ht", "ha", "hr", "haw",
  26. "bem", "ig", "rn", "id", "ia", "zu", "is", "it", "jw", "rw", "sw",
  27. "tlh", "kg", "mfe", "kri", "la", "lv", "to", "lt", "ln", "loz",
  28. "lua", "lg", "hu", "mg", "mt", "mi", "nl", "pcm", "no", "nso",
  29. "ny", "nn", "uz", "oc", "om", "xx-pirate", "pl", "pt-BR", "pt-PT",
  30. "ro", "rm", "qu", "nyn", "crs", "sq", "sd", "sk", "sl", "so", "st",
  31. "sr-ME", "sr-Latn", "su", "fi", "sv", "tg", "tt", "vi", "tn", "tum",
  32. "tr", "tk", "tw", "fy", "wo", "xh", "el", "be", "bg", "ky", "kk", "mk",
  33. "mn", "ru", "sr", "uk", "ka", "hy", "yi", "iw", "ug", "ur", "ar", "ps",
  34. "fa", "ti", "am", "ne", "mr", "hi", "bn", "pa", "gu", "or", "ta", "te",
  35. "kn", "ml", "si", "th", "lo", "my", "km", "chr", "ko", "zh-CN", "zh-TW", "ja"]
  36. time_range_support = True
  37. # based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
  38. default_hostname = 'www.google.com'
  39. country_to_hostname = {
  40. 'BG': 'www.google.bg', # Bulgaria
  41. 'CZ': 'www.google.cz', # Czech Republic
  42. 'DE': 'www.google.de', # Germany
  43. 'DK': 'www.google.dk', # Denmark
  44. 'AT': 'www.google.at', # Austria
  45. 'CH': 'www.google.ch', # Switzerland
  46. 'GR': 'www.google.gr', # Greece
  47. 'AU': 'www.google.com.au', # Australia
  48. 'CA': 'www.google.ca', # Canada
  49. 'GB': 'www.google.co.uk', # United Kingdom
  50. 'ID': 'www.google.co.id', # Indonesia
  51. 'IE': 'www.google.ie', # Ireland
  52. 'IN': 'www.google.co.in', # India
  53. 'MY': 'www.google.com.my', # Malaysia
  54. 'NZ': 'www.google.co.nz', # New Zealand
  55. 'PH': 'www.google.com.ph', # Philippines
  56. 'SG': 'www.google.com.sg', # Singapore
  57. # 'US': 'www.google.us', # United States, redirect to .com
  58. 'ZA': 'www.google.co.za', # South Africa
  59. 'AR': 'www.google.com.ar', # Argentina
  60. 'CL': 'www.google.cl', # Chile
  61. 'ES': 'www.google.es', # Spain
  62. 'MX': 'www.google.com.mx', # Mexico
  63. 'EE': 'www.google.ee', # Estonia
  64. 'FI': 'www.google.fi', # Finland
  65. 'BE': 'www.google.be', # Belgium
  66. 'FR': 'www.google.fr', # France
  67. 'IL': 'www.google.co.il', # Israel
  68. 'HR': 'www.google.hr', # Croatia
  69. 'HU': 'www.google.hu', # Hungary
  70. 'IT': 'www.google.it', # Italy
  71. 'JP': 'www.google.co.jp', # Japan
  72. 'KR': 'www.google.co.kr', # South Korea
  73. 'LT': 'www.google.lt', # Lithuania
  74. 'LV': 'www.google.lv', # Latvia
  75. 'NO': 'www.google.no', # Norway
  76. 'NL': 'www.google.nl', # Netherlands
  77. 'PL': 'www.google.pl', # Poland
  78. 'BR': 'www.google.com.br', # Brazil
  79. 'PT': 'www.google.pt', # Portugal
  80. 'RO': 'www.google.ro', # Romania
  81. 'RU': 'www.google.ru', # Russia
  82. 'SK': 'www.google.sk', # Slovakia
  83. 'SL': 'www.google.si', # Slovenia (SL -> si)
  84. 'SE': 'www.google.se', # Sweden
  85. 'TH': 'www.google.co.th', # Thailand
  86. 'TR': 'www.google.com.tr', # Turkey
  87. 'UA': 'www.google.com.ua', # Ukraine
  88. # 'CN': 'www.google.cn', # China, only from China ?
  89. 'HK': 'www.google.com.hk', # Hong Kong
  90. 'TW': 'www.google.com.tw' # Taiwan
  91. }
  92. # osm
  93. url_map = 'https://www.openstreetmap.org/'\
  94. + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
  95. # search-url
  96. search_path = '/search'
  97. search_url = ('https://{hostname}' +
  98. search_path +
  99. '?{query}&start={offset}&gws_rd=cr&gbv=1&lr={lang}&ei=x')
  100. time_range_search = "&tbs=qdr:{range}"
  101. time_range_dict = {'day': 'd',
  102. 'week': 'w',
  103. 'month': 'm',
  104. 'year': 'y'}
  105. # other URLs
  106. map_hostname_start = 'maps.google.'
  107. maps_path = '/maps'
  108. redirect_path = '/url'
  109. images_path = '/images'
  110. # specific xpath variables
  111. results_xpath = '//div[@class="g"]'
  112. url_xpath = './/h3/a/@href'
  113. title_xpath = './/h3'
  114. content_xpath = './/span[@class="st"]'
  115. content_misc_xpath = './/div[@class="f slp"]'
  116. suggestion_xpath = '//p[@class="_Bmc"]'
  117. # map : detail location
  118. map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'
  119. map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'
  120. map_website_url_xpath = 'h3[2]/a/@href'
  121. map_website_title_xpath = 'h3[2]'
  122. # map : near the location
  123. map_near = 'table[@class="ts"]//tr'
  124. map_near_title = './/h4'
  125. map_near_url = './/h4/a/@href'
  126. map_near_phone = './/span[@class="nobr"]'
  127. # images
  128. images_xpath = './/div/a'
  129. image_url_xpath = './@href'
  130. image_img_src_xpath = './img/@src'
  131. # property names
  132. # FIXME : no translation
  133. property_address = "Address"
  134. property_phone = "Phone number"
  135. # remove google-specific tracking-url
  136. def parse_url(url_string, google_hostname):
  137. # sanity check
  138. if url_string is None:
  139. return url_string
  140. # normal case
  141. parsed_url = urlparse(url_string)
  142. if (parsed_url.netloc in [google_hostname, '']
  143. and parsed_url.path == redirect_path):
  144. query = dict(parse_qsl(parsed_url.query))
  145. return query['q']
  146. else:
  147. return url_string
  148. # returns extract_text on the first result selected by the xpath or None
  149. def extract_text_from_dom(result, xpath):
  150. r = result.xpath(xpath)
  151. if len(r) > 0:
  152. return extract_text(r[0])
  153. return None
  154. # do search-request
  155. def request(query, params):
  156. offset = (params['pageno'] - 1) * 10
  157. if params['language'] == 'all':
  158. language = 'en'
  159. country = 'US'
  160. url_lang = ''
  161. elif params['language'][:2] == 'jv':
  162. language = 'jw'
  163. country = 'ID'
  164. url_lang = 'lang_jw'
  165. else:
  166. language_array = params['language'].lower().split('-')
  167. if len(language_array) == 2:
  168. country = language_array[1]
  169. else:
  170. country = 'US'
  171. language = language_array[0] + ',' + language_array[0] + '-' + country
  172. url_lang = 'lang_' + language_array[0]
  173. if use_locale_domain:
  174. google_hostname = country_to_hostname.get(country.upper(), default_hostname)
  175. else:
  176. google_hostname = default_hostname
  177. params['url'] = search_url.format(offset=offset,
  178. query=urlencode({'q': query}),
  179. hostname=google_hostname,
  180. lang=url_lang)
  181. if params['time_range'] in time_range_dict:
  182. params['url'] += time_range_search.format(range=time_range_dict[params['time_range']])
  183. params['headers']['Accept-Language'] = language
  184. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  185. params['google_hostname'] = google_hostname
  186. return params
  187. # get response from search-request
  188. def response(resp):
  189. results = []
  190. # detect google sorry
  191. resp_url = urlparse(resp.url)
  192. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  193. raise RuntimeWarning('sorry.google.com')
  194. # which hostname ?
  195. google_hostname = resp.search_params.get('google_hostname')
  196. google_url = "https://" + google_hostname
  197. # convert the text to dom
  198. dom = html.fromstring(resp.text)
  199. # parse results
  200. for result in dom.xpath(results_xpath):
  201. try:
  202. title = extract_text(result.xpath(title_xpath)[0])
  203. url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname)
  204. parsed_url = urlparse(url, google_hostname)
  205. # map result
  206. if parsed_url.netloc == google_hostname:
  207. # TODO fix inside links
  208. continue
  209. # if parsed_url.path.startswith(maps_path) or parsed_url.netloc.startswith(map_hostname_start):
  210. # print "yooooo"*30
  211. # x = result.xpath(map_near)
  212. # if len(x) > 0:
  213. # # map : near the location
  214. # results = results + parse_map_near(parsed_url, x, google_hostname)
  215. # else:
  216. # # map : detail about a location
  217. # results = results + parse_map_detail(parsed_url, result, google_hostname)
  218. # # google news
  219. # elif parsed_url.path == search_path:
  220. # # skipping news results
  221. # pass
  222. # # images result
  223. # elif parsed_url.path == images_path:
  224. # # only thumbnail image provided,
  225. # # so skipping image results
  226. # # results = results + parse_images(result, google_hostname)
  227. # pass
  228. else:
  229. # normal result
  230. content = extract_text_from_dom(result, content_xpath)
  231. if content is None:
  232. continue
  233. content_misc = extract_text_from_dom(result, content_misc_xpath)
  234. if content_misc is not None:
  235. content = content_misc + "<br />" + content
  236. # append result
  237. results.append({'url': url,
  238. 'title': title,
  239. 'content': content
  240. })
  241. except:
  242. logger.debug('result parse error in:\n%s', etree.tostring(result, pretty_print=True))
  243. continue
  244. # parse suggestion
  245. for suggestion in dom.xpath(suggestion_xpath):
  246. # append suggestion
  247. results.append({'suggestion': extract_text(suggestion)})
  248. # return results
  249. return results
  250. def parse_images(result, google_hostname):
  251. results = []
  252. for image in result.xpath(images_xpath):
  253. url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname)
  254. img_src = extract_text(image.xpath(image_img_src_xpath)[0])
  255. # append result
  256. results.append({'url': url,
  257. 'title': '',
  258. 'content': '',
  259. 'img_src': img_src,
  260. 'template': 'images.html'
  261. })
  262. return results
  263. def parse_map_near(parsed_url, x, google_hostname):
  264. results = []
  265. for result in x:
  266. title = extract_text_from_dom(result, map_near_title)
  267. url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname)
  268. attributes = []
  269. phone = extract_text_from_dom(result, map_near_phone)
  270. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  271. results.append({'title': title,
  272. 'url': url,
  273. 'content': attributes_to_html(attributes)
  274. })
  275. return results
  276. def parse_map_detail(parsed_url, result, google_hostname):
  277. results = []
  278. # try to parse the geoloc
  279. m = re.search(r'@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path)
  280. if m is None:
  281. m = re.search(r'll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query)
  282. if m is not None:
  283. # geoloc found (ignored)
  284. lon = float(m.group(2)) # noqa
  285. lat = float(m.group(1)) # noqa
  286. zoom = int(m.group(3)) # noqa
  287. # attributes
  288. attributes = []
  289. address = extract_text_from_dom(result, map_address_xpath)
  290. phone = extract_text_from_dom(result, map_phone_xpath)
  291. add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon))
  292. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  293. # title / content / url
  294. website_title = extract_text_from_dom(result, map_website_title_xpath)
  295. content = extract_text_from_dom(result, content_xpath)
  296. website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname)
  297. # add a result if there is a website
  298. if website_url is not None:
  299. results.append({'title': website_title,
  300. 'content': (content + '<br />' if content is not None else '')
  301. + attributes_to_html(attributes),
  302. 'url': website_url
  303. })
  304. return results
  305. def add_attributes(attributes, name, value, url):
  306. if value is not None and len(value) > 0:
  307. attributes.append({'label': name, 'value': value, 'url': url})
  308. def attributes_to_html(attributes):
  309. retval = '<table class="table table-striped">'
  310. for a in attributes:
  311. value = a.get('value')
  312. if 'url' in a:
  313. value = '<a href="' + a.get('url') + '">' + value + '</a>'
  314. retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>'
  315. retval = retval + '</table>'
  316. return retval