]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/openload.py
6 from ..compat
import compat_urlparse
17 def cookie_to_dict(cookie
):
20 'value': cookie
.value
,
22 if cookie
.port_specified
:
23 cookie_dict
['port'] = cookie
.port
24 if cookie
.domain_specified
:
25 cookie_dict
['domain'] = cookie
.domain
26 if cookie
.path_specified
:
27 cookie_dict
['path'] = cookie
.path
28 if cookie
.expires
is not None:
29 cookie_dict
['expires'] = cookie
.expires
30 if cookie
.secure
is not None:
31 cookie_dict
['secure'] = cookie
.secure
32 if cookie
.discard
is not None:
33 cookie_dict
['discard'] = cookie
.discard
35 if (cookie
.has_nonstandard_attr('httpOnly')
36 or cookie
.has_nonstandard_attr('httponly')
37 or cookie
.has_nonstandard_attr('HttpOnly')):
38 cookie_dict
['httponly'] = True
44 def cookie_jar_to_list(cookie_jar
):
45 return [cookie_to_dict(cookie
) for cookie
in cookie_jar
]
48 class PhantomJSwrapper
:
49 """PhantomJS wrapper class
51 This class is experimental.
55 phantom.onError = function(msg, trace) {{
56 var msgStack = ['PHANTOM ERROR: ' + msg];
57 if(trace && trace.length) {{
58 msgStack.push('TRACE:');
59 trace.forEach(function(t) {{
60 msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
61 + (t.function ? ' (in function ' + t.function +')' : ''));
64 console.error(msgStack.join('\n'));
67 var page = require('webpage').create();
68 var fs = require('fs');
69 var read = {{ mode: 'r', charset: 'utf-8' }};
70 var write = {{ mode: 'w', charset: 'utf-8' }};
71 JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
74 page.settings.resourceTimeout = {timeout};
75 page.settings.userAgent = "{ua}";
76 page.onLoadStarted = function() {{
77 page.evaluate(function() {{
78 delete window._phantom;
79 delete window.callPhantom;
82 var saveAndExit = function() {{
83 fs.write("{html}", page.content, write);
84 fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
87 page.onLoadFinished = function(status) {{
88 if(page.url === "") {{
89 page.setContent(fs.read("{html}", read), "{url}");
98 _TMP_FILE_NAMES
= ['script', 'html', 'cookies']
102 return get_exe_version('phantomjs', version_re
=r
'([0-9.]+)')
104 def __init__(self
, extractor
, required_version
=None, timeout
=10000):
107 self
.exe
= check_executable('phantomjs', ['-v'])
109 raise ExtractorError('PhantomJS executable not found in PATH, '
110 'download it from http://phantomjs.org',
113 self
.extractor
= extractor
116 version
= self
._version
()
117 if is_outdated_version(version
, required_version
):
118 self
.extractor
._downloader
.report_warning(
119 'Your copy of PhantomJS is outdated, update it to version '
120 '%s or newer if you encounter any errors.' % required_version
)
125 for name
in self
._TMP
_FILE
_NAMES
:
126 tmp
= tempfile
.NamedTemporaryFile(delete
=False)
128 self
._TMP
_FILES
[name
] = tmp
131 for name
in self
._TMP
_FILE
_NAMES
:
133 os
.remove(self
._TMP
_FILES
[name
].name
)
134 except (OSError, KeyError):
137 def _save_cookies(self
, url
):
138 cookies
= cookie_jar_to_list(self
.extractor
._downloader
.cookiejar
)
139 for cookie
in cookies
:
140 if 'path' not in cookie
:
142 if 'domain' not in cookie
:
143 cookie
['domain'] = compat_urlparse
.urlparse(url
).netloc
144 with open(self
._TMP
_FILES
['cookies'].name
, 'wb') as f
:
145 f
.write(json
.dumps(cookies
).encode('utf-8'))
147 def _load_cookies(self
):
148 with open(self
._TMP
_FILES
['cookies'].name
, 'rb') as f
:
149 cookies
= json
.loads(f
.read().decode('utf-8'))
150 for cookie
in cookies
:
151 if cookie
['httponly'] is True:
152 cookie
['rest'] = {'httpOnly': None}
153 if 'expiry' in cookie
:
154 cookie
['expire_time'] = cookie
['expiry']
155 self
.extractor
._set
_cookie
(**cookie
)
157 def get(self
, url
, html
=None, video_id
=None, note
=None, note2
='Executing JS on webpage', headers
={}, jscode
='saveAndExit();'):
159 Downloads webpage (if needed) and executes JS
163 html: optional, html code of website
165 note: optional, displayed when downloading webpage
166 note2: optional, displayed when executing JS
167 headers: custom http headers
168 jscode: code to be executed when page is loaded
171 * downloaded website (after JS execution)
172 * anything you print with `console.log` (but not inside `page.execute`!)
174 In most cases you don't need to add any `jscode`.
175 It is executed in `page.onLoadFinished`.
176 `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
177 It is possible to wait for some element on the webpage, for example:
178 var check = function() {
179 var elementFound = page.evaluate(function() {
180 return document.querySelector('#b.done') !== null;
185 window.setTimeout(check, 500);
188 page.evaluate(function(){
189 document.querySelector('#a').click();
193 if 'saveAndExit();' not in jscode
:
194 raise ExtractorError('`saveAndExit();` not found in `jscode`')
196 html
= self
.extractor
._download
_webpage
(url
, video_id
, note
=note
, headers
=headers
)
197 with open(self
._TMP
_FILES
['html'].name
, 'wb') as f
:
198 f
.write(html
.encode('utf-8'))
200 self
._save
_cookies
(url
)
202 replaces
= self
.options
203 replaces
['url'] = url
204 user_agent
= headers
.get('User-Agent') or self
.extractor
.get_param('http_headers')['User-Agent']
205 replaces
['ua'] = user_agent
.replace('"', '\\"')
206 replaces
['jscode'] = jscode
208 for x
in self
._TMP
_FILE
_NAMES
:
209 replaces
[x
] = self
._TMP
_FILES
[x
].name
.replace('\\', '\\\\').replace('"', '\\"')
211 with open(self
._TMP
_FILES
['script'].name
, 'wb') as f
:
212 f
.write(self
._TEMPLATE
.format(**replaces
).encode('utf-8'))
215 self
.extractor
.to_screen(f
'{note2}')
217 self
.extractor
.to_screen(f
'{video_id}: {note2}')
220 [self
.exe
, '--ssl-protocol=any', self
._TMP
_FILES
['script'].name
],
221 stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
222 out
, err
= p
.communicate_or_kill()
223 if p
.returncode
!= 0:
224 raise ExtractorError(
225 'Executing JS failed\n:' + encodeArgument(err
))
226 with open(self
._TMP
_FILES
['html'].name
, 'rb') as f
:
227 html
= f
.read().decode('utf-8')
231 return (html
, encodeArgument(out
))