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