]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/openload.py
7 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
34 with contextlib
.suppress(TypeError):
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
42 def cookie_jar_to_list(cookie_jar
):
43 return [cookie_to_dict(cookie
) for cookie
in cookie_jar
]
46 class PhantomJSwrapper
:
47 """PhantomJS wrapper class
49 This class is experimental.
53 phantom.onError = function(msg, trace) {{
54 var msgStack = ['PHANTOM ERROR: ' + msg];
55 if(trace && trace.length) {{
56 msgStack.push('TRACE:');
57 trace.forEach(function(t) {{
58 msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
59 + (t.function ? ' (in function ' + t.function +')' : ''));
62 console.error(msgStack.join('\n'));
65 var page = require('webpage').create();
66 var fs = require('fs');
67 var read = {{ mode: 'r', charset: 'utf-8' }};
68 var write = {{ mode: 'w', charset: 'utf-8' }};
69 JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
72 page.settings.resourceTimeout = {timeout};
73 page.settings.userAgent = "{ua}";
74 page.onLoadStarted = function() {{
75 page.evaluate(function() {{
76 delete window._phantom;
77 delete window.callPhantom;
80 var saveAndExit = function() {{
81 fs.write("{html}", page.content, write);
82 fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
85 page.onLoadFinished = function(status) {{
86 if(page.url === "") {{
87 page.setContent(fs.read("{html}", read), "{url}");
96 _TMP_FILE_NAMES
= ['script', 'html', 'cookies']
100 return get_exe_version('phantomjs', version_re
=r
'([0-9.]+)')
102 def __init__(self
, extractor
, required_version
=None, timeout
=10000):
105 self
.exe
= check_executable('phantomjs', ['-v'])
107 raise ExtractorError('PhantomJS executable not found in PATH, '
108 'download it from http://phantomjs.org',
111 self
.extractor
= extractor
114 version
= self
._version
()
115 if is_outdated_version(version
, required_version
):
116 self
.extractor
._downloader
.report_warning(
117 'Your copy of PhantomJS is outdated, update it to version '
118 '%s or newer if you encounter any errors.' % required_version
)
123 for name
in self
._TMP
_FILE
_NAMES
:
124 tmp
= tempfile
.NamedTemporaryFile(delete
=False)
126 self
._TMP
_FILES
[name
] = tmp
129 for name
in self
._TMP
_FILE
_NAMES
:
130 with contextlib
.suppress(OSError, KeyError):
131 os
.remove(self
._TMP
_FILES
[name
].name
)
133 def _save_cookies(self
, url
):
134 cookies
= cookie_jar_to_list(self
.extractor
._downloader
.cookiejar
)
135 for cookie
in cookies
:
136 if 'path' not in cookie
:
138 if 'domain' not in cookie
:
139 cookie
['domain'] = compat_urlparse
.urlparse(url
).netloc
140 with open(self
._TMP
_FILES
['cookies'].name
, 'wb') as f
:
141 f
.write(json
.dumps(cookies
).encode('utf-8'))
143 def _load_cookies(self
):
144 with open(self
._TMP
_FILES
['cookies'].name
, 'rb') as f
:
145 cookies
= json
.loads(f
.read().decode('utf-8'))
146 for cookie
in cookies
:
147 if cookie
['httponly'] is True:
148 cookie
['rest'] = {'httpOnly': None}
149 if 'expiry' in cookie
:
150 cookie
['expire_time'] = cookie
['expiry']
151 self
.extractor
._set
_cookie
(**cookie
)
153 def get(self
, url
, html
=None, video_id
=None, note
=None, note2
='Executing JS on webpage', headers
={}, jscode
='saveAndExit();'):
155 Downloads webpage (if needed) and executes JS
159 html: optional, html code of website
161 note: optional, displayed when downloading webpage
162 note2: optional, displayed when executing JS
163 headers: custom http headers
164 jscode: code to be executed when page is loaded
167 * downloaded website (after JS execution)
168 * anything you print with `console.log` (but not inside `page.execute`!)
170 In most cases you don't need to add any `jscode`.
171 It is executed in `page.onLoadFinished`.
172 `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
173 It is possible to wait for some element on the webpage, for example:
174 var check = function() {
175 var elementFound = page.evaluate(function() {
176 return document.querySelector('#b.done') !== null;
181 window.setTimeout(check, 500);
184 page.evaluate(function(){
185 document.querySelector('#a').click();
189 if 'saveAndExit();' not in jscode
:
190 raise ExtractorError('`saveAndExit();` not found in `jscode`')
192 html
= self
.extractor
._download
_webpage
(url
, video_id
, note
=note
, headers
=headers
)
193 with open(self
._TMP
_FILES
['html'].name
, 'wb') as f
:
194 f
.write(html
.encode('utf-8'))
196 self
._save
_cookies
(url
)
198 replaces
= self
.options
199 replaces
['url'] = url
200 user_agent
= headers
.get('User-Agent') or self
.extractor
.get_param('http_headers')['User-Agent']
201 replaces
['ua'] = user_agent
.replace('"', '\\"')
202 replaces
['jscode'] = jscode
204 for x
in self
._TMP
_FILE
_NAMES
:
205 replaces
[x
] = self
._TMP
_FILES
[x
].name
.replace('\\', '\\\\').replace('"', '\\"')
207 with open(self
._TMP
_FILES
['script'].name
, 'wb') as f
:
208 f
.write(self
._TEMPLATE
.format(**replaces
).encode('utf-8'))
211 self
.extractor
.to_screen(f
'{note2}')
213 self
.extractor
.to_screen(f
'{video_id}: {note2}')
215 stdout
, stderr
, returncode
= Popen
.run(
216 [self
.exe
, '--ssl-protocol=any', self
._TMP
_FILES
['script'].name
],
217 text
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
219 raise ExtractorError(f
'Executing JS failed:\n{stderr}')
220 with open(self
._TMP
_FILES
['html'].name
, 'rb') as f
:
221 html
= f
.read().decode('utf-8')