google.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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, etree
  15. from searx.engines.xpath import extract_text, extract_url
  16. from searx.search import logger
  17. logger = logger.getChild('google engine')
  18. # engine dependent config
  19. categories = ['general']
  20. paging = True
  21. language_support = True
  22. use_locale_domain = 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 State, 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', # Span
  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 Korean
  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', # Ikraine
  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}&gbv=1&gws_rd=ssl')
  86. # other URLs
  87. map_hostname_start = 'maps.google.'
  88. maps_path = '/maps'
  89. redirect_path = '/url'
  90. images_path = '/images'
  91. # specific xpath variables
  92. results_xpath = '//div[@class="g"]'
  93. url_xpath = './/h3/a/@href'
  94. title_xpath = './/h3'
  95. content_xpath = './/span[@class="st"]'
  96. content_misc_xpath = './/div[@class="f slp"]'
  97. suggestion_xpath = '//p[@class="_Bmc"]'
  98. # map : detail location
  99. map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'
  100. map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'
  101. map_website_url_xpath = 'h3[2]/a/@href'
  102. map_website_title_xpath = 'h3[2]'
  103. # map : near the location
  104. map_near = 'table[@class="ts"]//tr'
  105. map_near_title = './/h4'
  106. map_near_url = './/h4/a/@href'
  107. map_near_phone = './/span[@class="nobr"]'
  108. # images
  109. images_xpath = './/div/a'
  110. image_url_xpath = './@href'
  111. image_img_src_xpath = './img/@src'
  112. # property names
  113. # FIXME : no translation
  114. property_address = "Address"
  115. property_phone = "Phone number"
  116. # remove google-specific tracking-url
  117. def parse_url(url_string, google_hostname):
  118. # sanity check
  119. if url_string is None:
  120. return url_string
  121. # normal case
  122. parsed_url = urlparse(url_string)
  123. if (parsed_url.netloc in [google_hostname, '']
  124. and parsed_url.path == redirect_path):
  125. query = dict(parse_qsl(parsed_url.query))
  126. return query['q']
  127. else:
  128. return url_string
  129. # returns extract_text on the first result selected by the xpath or None
  130. def extract_text_from_dom(result, xpath):
  131. r = result.xpath(xpath)
  132. if len(r) > 0:
  133. return escape(extract_text(r[0]))
  134. return None
  135. # do search-request
  136. def request(query, params):
  137. offset = (params['pageno'] - 1) * 10
  138. if params['language'] == 'all':
  139. language = 'en'
  140. country = 'US'
  141. else:
  142. language_array = params['language'].lower().split('_')
  143. if len(language_array) == 2:
  144. country = language_array[1]
  145. else:
  146. country = 'US'
  147. language = language_array[0] + ',' + language_array[0] + '-' + country
  148. if use_locale_domain:
  149. google_hostname = country_to_hostname.get(country.upper(), default_hostname)
  150. else:
  151. google_hostname = default_hostname
  152. params['url'] = search_url.format(offset=offset,
  153. query=urlencode({'q': query}),
  154. hostname=google_hostname)
  155. params['headers']['Accept-Language'] = language
  156. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
  157. params['google_hostname'] = google_hostname
  158. return params
  159. # get response from search-request
  160. def response(resp):
  161. results = []
  162. # detect google sorry
  163. resp_url = urlparse(resp.url)
  164. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  165. raise RuntimeWarning('sorry.google.com')
  166. # which hostname ?
  167. google_hostname = resp.search_params.get('google_hostname')
  168. google_url = "https://" + google_hostname
  169. # convert the text to dom
  170. dom = html.fromstring(resp.text)
  171. # parse results
  172. for result in dom.xpath(results_xpath):
  173. try:
  174. title = extract_text(result.xpath(title_xpath)[0])
  175. url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname)
  176. parsed_url = urlparse(url, google_hostname)
  177. # map result
  178. if parsed_url.netloc == google_hostname:
  179. # TODO fix inside links
  180. continue
  181. # if parsed_url.path.startswith(maps_path) or parsed_url.netloc.startswith(map_hostname_start):
  182. # print "yooooo"*30
  183. # x = result.xpath(map_near)
  184. # if len(x) > 0:
  185. # # map : near the location
  186. # results = results + parse_map_near(parsed_url, x, google_hostname)
  187. # else:
  188. # # map : detail about a location
  189. # results = results + parse_map_detail(parsed_url, result, google_hostname)
  190. # # google news
  191. # elif parsed_url.path == search_path:
  192. # # skipping news results
  193. # pass
  194. # # images result
  195. # elif parsed_url.path == images_path:
  196. # # only thumbnail image provided,
  197. # # so skipping image results
  198. # # results = results + parse_images(result, google_hostname)
  199. # pass
  200. else:
  201. # normal result
  202. content = extract_text_from_dom(result, content_xpath)
  203. if content is None:
  204. continue
  205. content_misc = extract_text_from_dom(result, content_misc_xpath)
  206. if content_misc is not None:
  207. content = content_misc + "<br />" + content
  208. # append result
  209. results.append({'url': url,
  210. 'title': title,
  211. 'content': content
  212. })
  213. except:
  214. logger.debug('result parse error in:\n%s', etree.tostring(result, pretty_print=True))
  215. continue
  216. # parse suggestion
  217. for suggestion in dom.xpath(suggestion_xpath):
  218. # append suggestion
  219. results.append({'suggestion': escape(extract_text(suggestion))})
  220. # return results
  221. return results
  222. def parse_images(result, google_hostname):
  223. results = []
  224. for image in result.xpath(images_xpath):
  225. url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname)
  226. img_src = extract_text(image.xpath(image_img_src_xpath)[0])
  227. # append result
  228. results.append({'url': url,
  229. 'title': '',
  230. 'content': '',
  231. 'img_src': img_src,
  232. 'template': 'images.html'
  233. })
  234. return results
  235. def parse_map_near(parsed_url, x, google_hostname):
  236. results = []
  237. for result in x:
  238. title = extract_text_from_dom(result, map_near_title)
  239. url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname)
  240. attributes = []
  241. phone = extract_text_from_dom(result, map_near_phone)
  242. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  243. results.append({'title': title,
  244. 'url': url,
  245. 'content': attributes_to_html(attributes)
  246. })
  247. return results
  248. def parse_map_detail(parsed_url, result, google_hostname):
  249. results = []
  250. # try to parse the geoloc
  251. m = re.search('@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path)
  252. if m is None:
  253. m = re.search('ll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query)
  254. if m is not None:
  255. # geoloc found (ignored)
  256. lon = float(m.group(2)) # noqa
  257. lat = float(m.group(1)) # noqa
  258. zoom = int(m.group(3)) # noqa
  259. # attributes
  260. attributes = []
  261. address = extract_text_from_dom(result, map_address_xpath)
  262. phone = extract_text_from_dom(result, map_phone_xpath)
  263. add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon))
  264. add_attributes(attributes, property_phone, phone, 'tel:' + phone)
  265. # title / content / url
  266. website_title = extract_text_from_dom(result, map_website_title_xpath)
  267. content = extract_text_from_dom(result, content_xpath)
  268. website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname)
  269. # add a result if there is a website
  270. if website_url is not None:
  271. results.append({'title': website_title,
  272. 'content': (content + '<br />' if content is not None else '')
  273. + attributes_to_html(attributes),
  274. 'url': website_url
  275. })
  276. return results
  277. def add_attributes(attributes, name, value, url):
  278. if value is not None and len(value) > 0:
  279. attributes.append({'label': name, 'value': value, 'url': url})
  280. def attributes_to_html(attributes):
  281. retval = '<table class="table table-striped">'
  282. for a in attributes:
  283. value = a.get('value')
  284. if 'url' in a:
  285. value = '<a href="' + a.get('url') + '">' + value + '</a>'
  286. retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>'
  287. retval = retval + '</table>'
  288. return retval