You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
8.0 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import os
  5. import subprocess
  6. import tempfile
  7. from ..compat import (
  8. compat_urlparse,
  9. compat_kwargs,
  10. )
  11. from ..utils import (
  12. check_executable,
  13. encodeArgument,
  14. ExtractorError,
  15. get_exe_version,
  16. is_outdated_version,
  17. std_headers,
  18. )
  19. def cookie_to_dict(cookie):
  20. cookie_dict = {
  21. 'name': cookie.name,
  22. 'value': cookie.value,
  23. }
  24. if cookie.port_specified:
  25. cookie_dict['port'] = cookie.port
  26. if cookie.domain_specified:
  27. cookie_dict['domain'] = cookie.domain
  28. if cookie.path_specified:
  29. cookie_dict['path'] = cookie.path
  30. if cookie.expires is not None:
  31. cookie_dict['expires'] = cookie.expires
  32. if cookie.secure is not None:
  33. cookie_dict['secure'] = cookie.secure
  34. if cookie.discard is not None:
  35. cookie_dict['discard'] = cookie.discard
  36. try:
  37. if (cookie.has_nonstandard_attr('httpOnly')
  38. or cookie.has_nonstandard_attr('httponly')
  39. or cookie.has_nonstandard_attr('HttpOnly')):
  40. cookie_dict['httponly'] = True
  41. except TypeError:
  42. pass
  43. return cookie_dict
  44. def cookie_jar_to_list(cookie_jar):
  45. return [cookie_to_dict(cookie) for cookie in cookie_jar]
  46. class PhantomJSwrapper(object):
  47. """PhantomJS wrapper class
  48. This class is experimental.
  49. """
  50. _TEMPLATE = r'''
  51. phantom.onError = function(msg, trace) {{
  52. var msgStack = ['PHANTOM ERROR: ' + msg];
  53. if(trace && trace.length) {{
  54. msgStack.push('TRACE:');
  55. trace.forEach(function(t) {{
  56. msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
  57. + (t.function ? ' (in function ' + t.function +')' : ''));
  58. }});
  59. }}
  60. console.error(msgStack.join('\n'));
  61. phantom.exit(1);
  62. }};
  63. var page = require('webpage').create();
  64. var fs = require('fs');
  65. var read = {{ mode: 'r', charset: 'utf-8' }};
  66. var write = {{ mode: 'w', charset: 'utf-8' }};
  67. JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
  68. phantom.addCookie(x);
  69. }});
  70. page.settings.resourceTimeout = {timeout};
  71. page.settings.userAgent = "{ua}";
  72. page.onLoadStarted = function() {{
  73. page.evaluate(function() {{
  74. delete window._phantom;
  75. delete window.callPhantom;
  76. }});
  77. }};
  78. var saveAndExit = function() {{
  79. fs.write("{html}", page.content, write);
  80. fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
  81. phantom.exit();
  82. }};
  83. page.onLoadFinished = function(status) {{
  84. if(page.url === "") {{
  85. page.setContent(fs.read("{html}", read), "{url}");
  86. }}
  87. else {{
  88. {jscode}
  89. }}
  90. }};
  91. page.open("");
  92. '''
  93. _TMP_FILE_NAMES = ['script', 'html', 'cookies']
  94. @staticmethod
  95. def _version():
  96. return get_exe_version('phantomjs', version_re=r'([0-9.]+)')
  97. def __init__(self, extractor, required_version=None, timeout=10000):
  98. self._TMP_FILES = {}
  99. self.exe = check_executable('phantomjs', ['-v'])
  100. if not self.exe:
  101. raise ExtractorError('PhantomJS executable not found in PATH, '
  102. 'download it from http://phantomjs.org',
  103. expected=True)
  104. self.extractor = extractor
  105. if required_version:
  106. version = self._version()
  107. if is_outdated_version(version, required_version):
  108. self.extractor._downloader.report_warning(
  109. 'Your copy of PhantomJS is outdated, update it to version '
  110. '%s or newer if you encounter any errors.' % required_version)
  111. self.options = {
  112. 'timeout': timeout,
  113. }
  114. for name in self._TMP_FILE_NAMES:
  115. tmp = tempfile.NamedTemporaryFile(delete=False)
  116. tmp.close()
  117. self._TMP_FILES[name] = tmp
  118. def __del__(self):
  119. for name in self._TMP_FILE_NAMES:
  120. try:
  121. os.remove(self._TMP_FILES[name].name)
  122. except (IOError, OSError, KeyError):
  123. pass
  124. def _save_cookies(self, url):
  125. cookies = cookie_jar_to_list(self.extractor._downloader.cookiejar)
  126. for cookie in cookies:
  127. if 'path' not in cookie:
  128. cookie['path'] = '/'
  129. if 'domain' not in cookie:
  130. cookie['domain'] = compat_urlparse.urlparse(url).netloc
  131. with open(self._TMP_FILES['cookies'].name, 'wb') as f:
  132. f.write(json.dumps(cookies).encode('utf-8'))
  133. def _load_cookies(self):
  134. with open(self._TMP_FILES['cookies'].name, 'rb') as f:
  135. cookies = json.loads(f.read().decode('utf-8'))
  136. for cookie in cookies:
  137. if cookie['httponly'] is True:
  138. cookie['rest'] = {'httpOnly': None}
  139. if 'expiry' in cookie:
  140. cookie['expire_time'] = cookie['expiry']
  141. self.extractor._set_cookie(**compat_kwargs(cookie))
  142. def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
  143. """
  144. Downloads webpage (if needed) and executes JS
  145. Params:
  146. url: website url
  147. html: optional, html code of website
  148. video_id: video id
  149. note: optional, displayed when downloading webpage
  150. note2: optional, displayed when executing JS
  151. headers: custom http headers
  152. jscode: code to be executed when page is loaded
  153. Returns tuple with:
  154. * downloaded website (after JS execution)
  155. * anything you print with `console.log` (but not inside `page.execute`!)
  156. In most cases you don't need to add any `jscode`.
  157. It is executed in `page.onLoadFinished`.
  158. `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
  159. It is possible to wait for some element on the webpage, for example:
  160. var check = function() {
  161. var elementFound = page.evaluate(function() {
  162. return document.querySelector('#b.done') !== null;
  163. });
  164. if(elementFound)
  165. saveAndExit();
  166. else
  167. window.setTimeout(check, 500);
  168. }
  169. page.evaluate(function(){
  170. document.querySelector('#a').click();
  171. });
  172. check();
  173. """
  174. if 'saveAndExit();' not in jscode:
  175. raise ExtractorError('`saveAndExit();` not found in `jscode`')
  176. if not html:
  177. html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
  178. with open(self._TMP_FILES['html'].name, 'wb') as f:
  179. f.write(html.encode('utf-8'))
  180. self._save_cookies(url)
  181. replaces = self.options
  182. replaces['url'] = url
  183. user_agent = headers.get('User-Agent') or std_headers['User-Agent']
  184. replaces['ua'] = user_agent.replace('"', '\\"')
  185. replaces['jscode'] = jscode
  186. for x in self._TMP_FILE_NAMES:
  187. replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
  188. with open(self._TMP_FILES['script'].name, 'wb') as f:
  189. f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
  190. if video_id is None:
  191. self.extractor.to_screen('%s' % (note2,))
  192. else:
  193. self.extractor.to_screen('%s: %s' % (video_id, note2))
  194. p = subprocess.Popen([
  195. self.exe, '--ssl-protocol=any',
  196. self._TMP_FILES['script'].name
  197. ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  198. out, err = p.communicate()
  199. if p.returncode != 0:
  200. raise ExtractorError(
  201. 'Executing JS failed\n:' + encodeArgument(err))
  202. with open(self._TMP_FILES['html'].name, 'rb') as f:
  203. html = f.read().decode('utf-8')
  204. self._load_cookies()
  205. return (html, encodeArgument(out))