code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def throttling_swap(d: list, e: int):
"""Swap positions of the 0'th and e'th elements in-place."""
e = throttling_mod_func(d, e)
f = d[0]
d[0] = d[e]
d[e] = f
|
Swap positions of the 0'th and e'th elements in-place.
|
throttling_swap
|
python
|
pytube/pytube
|
pytube/cipher.py
|
https://github.com/pytube/pytube/blob/master/pytube/cipher.py
|
Unlicense
|
def map_functions(js_func: str) -> Callable:
"""For a given JavaScript transform function, return the Python equivalent.
:param str js_func:
The JavaScript version of the transform function.
"""
mapper = (
# function(a){a.reverse()}
(r"{\w\.reverse\(\)}", reverse),
# function(a,b){a.splice(0,b)}
(r"{\w\.splice\(0,\w\)}", splice),
# function(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c}
(r"{var\s\w=\w\[0\];\w\[0\]=\w\[\w\%\w.length\];\w\[\w\]=\w}", swap),
# function(a,b){var c=a[0];a[0]=a[b%a.length];a[b%a.length]=c}
(
r"{var\s\w=\w\[0\];\w\[0\]=\w\[\w\%\w.length\];\w\[\w\%\w.length\]=\w}",
swap,
),
)
for pattern, fn in mapper:
if re.search(pattern, js_func):
return fn
raise RegexMatchError(caller="map_functions", pattern="multiple")
|
For a given JavaScript transform function, return the Python equivalent.
:param str js_func:
The JavaScript version of the transform function.
|
map_functions
|
python
|
pytube/pytube
|
pytube/cipher.py
|
https://github.com/pytube/pytube/blob/master/pytube/cipher.py
|
Unlicense
|
def main():
"""Command line application to download youtube videos."""
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(description=main.__doc__)
args = _parse_args(parser)
if args.verbose:
log_filename = None
if args.logfile:
log_filename = args.logfile
setup_logger(logging.DEBUG, log_filename=log_filename)
logger.debug(f'Pytube version: {__version__}')
if not args.url or "youtu" not in args.url:
parser.print_help()
sys.exit(1)
if "/playlist" in args.url:
print("Loading playlist...")
playlist = Playlist(args.url)
if not args.target:
args.target = safe_filename(playlist.title)
for youtube_video in playlist.videos:
try:
_perform_args_on_youtube(youtube_video, args)
except exceptions.PytubeError as e:
print(f"There was an error with video: {youtube_video}")
print(e)
else:
print("Loading video...")
youtube = YouTube(args.url)
_perform_args_on_youtube(youtube, args)
|
Command line application to download youtube videos.
|
main
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def build_playback_report(youtube: YouTube) -> None:
"""Serialize the request data to json for offline debugging.
:param YouTube youtube:
A YouTube object.
"""
ts = int(dt.datetime.utcnow().timestamp())
fp = os.path.join(os.getcwd(), f"yt-video-{youtube.video_id}-{ts}.json.gz")
js = youtube.js
watch_html = youtube.watch_html
vid_info = youtube.vid_info
with gzip.open(fp, "wb") as fh:
fh.write(
json.dumps(
{
"url": youtube.watch_url,
"js": js,
"watch_html": watch_html,
"video_info": vid_info,
}
).encode("utf8"),
)
|
Serialize the request data to json for offline debugging.
:param YouTube youtube:
A YouTube object.
|
build_playback_report
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def _unique_name(base: str, subtype: str, media_type: str, target: str) -> str:
"""
Given a base name, the file format, and the target directory, will generate
a filename unique for that directory and file format.
:param str base:
The given base-name.
:param str subtype:
The filetype of the video which will be downloaded.
:param str media_type:
The media_type of the file, ie. "audio" or "video"
:param Path target:
Target directory for download.
"""
counter = 0
while True:
file_name = f"{base}_{media_type}_{counter}"
file_path = os.path.join(target, f"{file_name}.{subtype}")
if not os.path.exists(file_path):
return file_name
counter += 1
|
Given a base name, the file format, and the target directory, will generate
a filename unique for that directory and file format.
:param str base:
The given base-name.
:param str subtype:
The filetype of the video which will be downloaded.
:param str media_type:
The media_type of the file, ie. "audio" or "video"
:param Path target:
Target directory for download.
|
_unique_name
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def ffmpeg_process(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""
Decides the correct video stream to download, then calls _ffmpeg_downloader.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
"""
youtube.register_on_progress_callback(on_progress)
target = target or os.getcwd()
if resolution == "best":
highest_quality_stream = (
youtube.streams.filter(progressive=False)
.order_by("resolution")
.last()
)
mp4_stream = (
youtube.streams.filter(progressive=False, subtype="mp4")
.order_by("resolution")
.last()
)
if highest_quality_stream.resolution == mp4_stream.resolution:
video_stream = mp4_stream
else:
video_stream = highest_quality_stream
else:
video_stream = youtube.streams.filter(
progressive=False, resolution=resolution, subtype="mp4"
).first()
if not video_stream:
video_stream = youtube.streams.filter(
progressive=False, resolution=resolution
).first()
if video_stream is None:
print(f"Could not find a stream with resolution: {resolution}")
print("Try one of these:")
display_streams(youtube)
sys.exit()
audio_stream = youtube.streams.get_audio_only(video_stream.subtype)
if not audio_stream:
audio_stream = (
youtube.streams.filter(only_audio=True).order_by("abr").last()
)
if not audio_stream:
print("Could not find an audio only stream")
sys.exit()
_ffmpeg_downloader(
audio_stream=audio_stream, video_stream=video_stream, target=target
)
|
Decides the correct video stream to download, then calls _ffmpeg_downloader.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
|
ffmpeg_process
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def _ffmpeg_downloader(
audio_stream: Stream, video_stream: Stream, target: str
) -> None:
"""
Given a YouTube Stream object, finds the correct audio stream, downloads them both
giving them a unique name, them uses ffmpeg to create a new file with the audio
and video from the previously downloaded files. Then deletes the original adaptive
streams, leaving the combination.
:param Stream audio_stream:
A valid Stream object representing the audio to download
:param Stream video_stream:
A valid Stream object representing the video to download
:param Path target:
A valid Path object
"""
video_unique_name = _unique_name(
safe_filename(video_stream.title),
video_stream.subtype,
"video",
target=target,
)
audio_unique_name = _unique_name(
safe_filename(video_stream.title),
audio_stream.subtype,
"audio",
target=target,
)
_download(stream=video_stream, target=target, filename=video_unique_name)
print("Loading audio...")
_download(stream=audio_stream, target=target, filename=audio_unique_name)
video_path = os.path.join(
target, f"{video_unique_name}.{video_stream.subtype}"
)
audio_path = os.path.join(
target, f"{audio_unique_name}.{audio_stream.subtype}"
)
final_path = os.path.join(
target, f"{safe_filename(video_stream.title)}.{video_stream.subtype}"
)
subprocess.run( # nosec
[
"ffmpeg",
"-i",
video_path,
"-i",
audio_path,
"-codec",
"copy",
final_path,
]
)
os.unlink(video_path)
os.unlink(audio_path)
|
Given a YouTube Stream object, finds the correct audio stream, downloads them both
giving them a unique name, them uses ffmpeg to create a new file with the audio
and video from the previously downloaded files. Then deletes the original adaptive
streams, leaving the combination.
:param Stream audio_stream:
A valid Stream object representing the audio to download
:param Stream video_stream:
A valid Stream object representing the video to download
:param Path target:
A valid Path object
|
_ffmpeg_downloader
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def download_by_itag(
youtube: YouTube, itag: int, target: Optional[str] = None
) -> None:
"""Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param int itag:
YouTube format identifier code.
:param str target:
Target directory for download
"""
stream = youtube.streams.get_by_itag(itag)
if stream is None:
print(f"Could not find a stream with itag: {itag}")
print("Try one of these:")
display_streams(youtube)
sys.exit()
youtube.register_on_progress_callback(on_progress)
try:
_download(stream, target=target)
except KeyboardInterrupt:
sys.exit()
|
Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param int itag:
YouTube format identifier code.
:param str target:
Target directory for download
|
download_by_itag
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def download_by_resolution(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
"""
# TODO(nficano): allow dash itags to be selected
stream = youtube.streams.get_by_resolution(resolution)
if stream is None:
print(f"Could not find a stream with resolution: {resolution}")
print("Try one of these:")
display_streams(youtube)
sys.exit()
youtube.register_on_progress_callback(on_progress)
try:
_download(stream, target=target)
except KeyboardInterrupt:
sys.exit()
|
Start downloading a YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
|
download_by_resolution
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def download_highest_resolution_progressive(
youtube: YouTube, resolution: str, target: Optional[str] = None
) -> None:
"""Start downloading the highest resolution progressive stream.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
"""
youtube.register_on_progress_callback(on_progress)
try:
stream = youtube.streams.get_highest_resolution()
except exceptions.VideoUnavailable as err:
print(f"No video streams available: {err}")
else:
try:
_download(stream, target=target)
except KeyboardInterrupt:
sys.exit()
|
Start downloading the highest resolution progressive stream.
:param YouTube youtube:
A valid YouTube object.
:param str resolution:
YouTube video resolution.
:param str target:
Target directory for download
|
download_highest_resolution_progressive
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def download_caption(
youtube: YouTube, lang_code: Optional[str], target: Optional[str] = None
) -> None:
"""Download a caption for the YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str lang_code:
Language code desired for caption file.
Prints available codes if the value is None
or the desired code is not available.
:param str target:
Target directory for download
"""
try:
caption = youtube.captions[lang_code]
downloaded_path = caption.download(
title=youtube.title, output_path=target
)
print(f"Saved caption file to: {downloaded_path}")
except KeyError:
print(f"Unable to find caption with code: {lang_code}")
_print_available_captions(youtube.captions)
|
Download a caption for the YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str lang_code:
Language code desired for caption file.
Prints available codes if the value is None
or the desired code is not available.
:param str target:
Target directory for download
|
download_caption
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def download_audio(
youtube: YouTube, filetype: str, target: Optional[str] = None
) -> None:
"""
Given a filetype, downloads the highest quality available audio stream for a
YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str filetype:
Desired file format to download.
:param str target:
Target directory for download
"""
audio = (
youtube.streams.filter(only_audio=True, subtype=filetype)
.order_by("abr")
.last()
)
if audio is None:
print("No audio only stream found. Try one of these:")
display_streams(youtube)
sys.exit()
youtube.register_on_progress_callback(on_progress)
try:
_download(audio, target=target)
except KeyboardInterrupt:
sys.exit()
|
Given a filetype, downloads the highest quality available audio stream for a
YouTube video.
:param YouTube youtube:
A valid YouTube object.
:param str filetype:
Desired file format to download.
:param str target:
Target directory for download
|
download_audio
|
python
|
pytube/pytube
|
pytube/cli.py
|
https://github.com/pytube/pytube/blob/master/pytube/cli.py
|
Unlicense
|
def __init__(self, caller: str, pattern: Union[str, Pattern]):
"""
:param str caller:
Calling function
:param str pattern:
Pattern that failed to match
"""
super().__init__(f"{caller}: could not find match for {pattern}")
self.caller = caller
self.pattern = pattern
|
:param str caller:
Calling function
:param str pattern:
Pattern that failed to match
|
__init__
|
python
|
pytube/pytube
|
pytube/exceptions.py
|
https://github.com/pytube/pytube/blob/master/pytube/exceptions.py
|
Unlicense
|
def publish_date(watch_html: str):
"""Extract publish date
:param str watch_html:
The html contents of the watch page.
:rtype: str
:returns:
Publish date of the video.
"""
try:
result = regex_search(
r"(?<=itemprop=\"datePublished\" content=\")\d{4}-\d{2}-\d{2}",
watch_html, group=0
)
except RegexMatchError:
return None
return datetime.strptime(result, '%Y-%m-%d')
|
Extract publish date
:param str watch_html:
The html contents of the watch page.
:rtype: str
:returns:
Publish date of the video.
|
publish_date
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def recording_available(watch_html):
"""Check if live stream recording is available.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
"""
unavailable_strings = [
'This live stream recording is not available.'
]
for string in unavailable_strings:
if string in watch_html:
return False
return True
|
Check if live stream recording is available.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
|
recording_available
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def is_private(watch_html):
"""Check if content is private.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
"""
private_strings = [
"This is a private video. Please sign in to verify that you may see it.",
"\"simpleText\":\"Private video\"",
"This video is private."
]
for string in private_strings:
if string in watch_html:
return True
return False
|
Check if content is private.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is private.
|
is_private
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def is_age_restricted(watch_html: str) -> bool:
"""Check if content is age restricted.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is age restricted.
"""
try:
regex_search(r"og:restrictions:age", watch_html, group=0)
except RegexMatchError:
return False
return True
|
Check if content is age restricted.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Whether or not the content is age restricted.
|
is_age_restricted
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def playability_status(watch_html: str) -> (str, str):
"""Return the playability status and status explanation of a video.
For example, a video may have a status of LOGIN_REQUIRED, and an explanation
of "This is a private video. Please sign in to verify that you may see it."
This explanation is what gets incorporated into the media player overlay.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Playability status and reason of the video.
"""
player_response = initial_player_response(watch_html)
status_dict = player_response.get('playabilityStatus', {})
if 'liveStreamability' in status_dict:
return 'LIVE_STREAM', 'Video is a live stream.'
if 'status' in status_dict:
if 'reason' in status_dict:
return status_dict['status'], [status_dict['reason']]
if 'messages' in status_dict:
return status_dict['status'], status_dict['messages']
return None, [None]
|
Return the playability status and status explanation of a video.
For example, a video may have a status of LOGIN_REQUIRED, and an explanation
of "This is a private video. Please sign in to verify that you may see it."
This explanation is what gets incorporated into the media player overlay.
:param str watch_html:
The html contents of the watch page.
:rtype: bool
:returns:
Playability status and reason of the video.
|
playability_status
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def channel_name(url: str) -> str:
"""Extract the ``channel_name`` or ``channel_id`` from a YouTube url.
This function supports the following patterns:
- :samp:`https://youtube.com/c/{channel_name}/*`
- :samp:`https://youtube.com/channel/{channel_id}/*
- :samp:`https://youtube.com/u/{channel_name}/*`
- :samp:`https://youtube.com/user/{channel_id}/*
:param str url:
A YouTube url containing a channel name.
:rtype: str
:returns:
YouTube channel name.
"""
patterns = [
r"(?:\/(c)\/([%\d\w_\-]+)(\/.*)?)",
r"(?:\/(channel)\/([%\w\d_\-]+)(\/.*)?)",
r"(?:\/(u)\/([%\d\w_\-]+)(\/.*)?)",
r"(?:\/(user)\/([%\w\d_\-]+)(\/.*)?)"
]
for pattern in patterns:
regex = re.compile(pattern)
function_match = regex.search(url)
if function_match:
logger.debug("finished regex search, matched: %s", pattern)
uri_style = function_match.group(1)
uri_identifier = function_match.group(2)
return f'/{uri_style}/{uri_identifier}'
raise RegexMatchError(
caller="channel_name", pattern="patterns"
)
|
Extract the ``channel_name`` or ``channel_id`` from a YouTube url.
This function supports the following patterns:
- :samp:`https://youtube.com/c/{channel_name}/*`
- :samp:`https://youtube.com/channel/{channel_id}/*
- :samp:`https://youtube.com/u/{channel_name}/*`
- :samp:`https://youtube.com/user/{channel_id}/*
:param str url:
A YouTube url containing a channel name.
:rtype: str
:returns:
YouTube channel name.
|
channel_name
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def video_info_url(video_id: str, watch_url: str) -> str:
"""Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str watch_url:
A YouTube watch url.
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
"""
params = OrderedDict(
[
("video_id", video_id),
("ps", "default"),
("eurl", quote(watch_url)),
("hl", "en_US"),
("html5", "1"),
("c", "TVHTML5"),
("cver", "7.20201028"),
]
)
return _video_info_url(params)
|
Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str watch_url:
A YouTube watch url.
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
|
video_info_url
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def video_info_url_age_restricted(video_id: str, embed_html: str) -> str:
"""Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str embed_html:
The html contents of the embed page (for age restricted videos).
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
"""
try:
sts = regex_search(r'"sts"\s*:\s*(\d+)', embed_html, group=1)
except RegexMatchError:
sts = ""
# Here we use ``OrderedDict`` so that the output is consistent between
# Python 2.7+.
eurl = f"https://youtube.googleapis.com/v/{video_id}"
params = OrderedDict(
[
("video_id", video_id),
("eurl", eurl),
("sts", sts),
("html5", "1"),
("c", "TVHTML5"),
("cver", "7.20201028"),
]
)
return _video_info_url(params)
|
Construct the video_info url.
:param str video_id:
A YouTube video identifier.
:param str embed_html:
The html contents of the embed page (for age restricted videos).
:rtype: str
:returns:
:samp:`https://youtube.com/get_video_info` with necessary GET
parameters.
|
video_info_url_age_restricted
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def js_url(html: str) -> str:
"""Get the base JavaScript url.
Construct the base JavaScript url, which contains the decipher
"transforms".
:param str html:
The html contents of the watch page.
"""
try:
base_js = get_ytplayer_config(html)['assets']['js']
except (KeyError, RegexMatchError):
base_js = get_ytplayer_js(html)
return "https://youtube.com" + base_js
|
Get the base JavaScript url.
Construct the base JavaScript url, which contains the decipher
"transforms".
:param str html:
The html contents of the watch page.
|
js_url
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def mime_type_codec(mime_type_codec: str) -> Tuple[str, List[str]]:
"""Parse the type data.
Breaks up the data in the ``type`` key of the manifest, which contains the
mime type and codecs serialized together, and splits them into separate
elements.
**Example**:
mime_type_codec('audio/webm; codecs="opus"') -> ('audio/webm', ['opus'])
:param str mime_type_codec:
String containing mime type and codecs.
:rtype: tuple
:returns:
The mime type and a list of codecs.
"""
pattern = r"(\w+\/\w+)\;\scodecs=\"([a-zA-Z-0-9.,\s]*)\""
regex = re.compile(pattern)
results = regex.search(mime_type_codec)
if not results:
raise RegexMatchError(caller="mime_type_codec", pattern=pattern)
mime_type, codecs = results.groups()
return mime_type, [c.strip() for c in codecs.split(",")]
|
Parse the type data.
Breaks up the data in the ``type`` key of the manifest, which contains the
mime type and codecs serialized together, and splits them into separate
elements.
**Example**:
mime_type_codec('audio/webm; codecs="opus"') -> ('audio/webm', ['opus'])
:param str mime_type_codec:
String containing mime type and codecs.
:rtype: tuple
:returns:
The mime type and a list of codecs.
|
mime_type_codec
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def get_ytplayer_js(html: str) -> Any:
"""Get the YouTube player base JavaScript path.
:param str html
The html contents of the watch page.
:rtype: str
:returns:
Path to YouTube's base.js file.
"""
js_url_patterns = [
r"(/s/player/[\w\d]+/[\w\d_/.]+/base\.js)"
]
for pattern in js_url_patterns:
regex = re.compile(pattern)
function_match = regex.search(html)
if function_match:
logger.debug("finished regex search, matched: %s", pattern)
yt_player_js = function_match.group(1)
return yt_player_js
raise RegexMatchError(
caller="get_ytplayer_js", pattern="js_url_patterns"
)
|
Get the YouTube player base JavaScript path.
:param str html
The html contents of the watch page.
:rtype: str
:returns:
Path to YouTube's base.js file.
|
get_ytplayer_js
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def get_ytplayer_config(html: str) -> Any:
"""Get the YouTube player configuration data from the watch html.
Extract the ``ytplayer_config``, which is json data embedded within the
watch html and serves as the primary source of obtaining the stream
manifest data.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html containing the encoded manifest data.
"""
logger.debug("finding initial function name")
config_patterns = [
r"ytplayer\.config\s*=\s*",
r"ytInitialPlayerResponse\s*=\s*"
]
for pattern in config_patterns:
# Try each pattern consecutively if they don't find a match
try:
return parse_for_object(html, pattern)
except HTMLParseError as e:
logger.debug(f'Pattern failed: {pattern}')
logger.debug(e)
continue
# setConfig() needs to be handled a little differently.
# We want to parse the entire argument to setConfig()
# and use then load that as json to find PLAYER_CONFIG
# inside of it.
setconfig_patterns = [
r"yt\.setConfig\(.*['\"]PLAYER_CONFIG['\"]:\s*"
]
for pattern in setconfig_patterns:
# Try each pattern consecutively if they don't find a match
try:
return parse_for_object(html, pattern)
except HTMLParseError:
continue
raise RegexMatchError(
caller="get_ytplayer_config", pattern="config_patterns, setconfig_patterns"
)
|
Get the YouTube player configuration data from the watch html.
Extract the ``ytplayer_config``, which is json data embedded within the
watch html and serves as the primary source of obtaining the stream
manifest data.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html containing the encoded manifest data.
|
get_ytplayer_config
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def get_ytcfg(html: str) -> str:
"""Get the entirety of the ytcfg object.
This is built over multiple pieces, so we have to find all matches and
combine the dicts together.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html containing the encoded manifest data.
"""
ytcfg = {}
ytcfg_patterns = [
r"ytcfg\s=\s",
r"ytcfg\.set\("
]
for pattern in ytcfg_patterns:
# Try each pattern consecutively and try to build a cohesive object
try:
found_objects = parse_for_all_objects(html, pattern)
for obj in found_objects:
ytcfg.update(obj)
except HTMLParseError:
continue
if len(ytcfg) > 0:
return ytcfg
raise RegexMatchError(
caller="get_ytcfg", pattern="ytcfg_pattenrs"
)
|
Get the entirety of the ytcfg object.
This is built over multiple pieces, so we have to find all matches and
combine the dicts together.
:param str html:
The html contents of the watch page.
:rtype: str
:returns:
Substring of the html containing the encoded manifest data.
|
get_ytcfg
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def apply_signature(stream_manifest: Dict, vid_info: Dict, js: str) -> None:
"""Apply the decrypted signature to the stream manifest.
:param dict stream_manifest:
Details of the media streams available.
:param str js:
The contents of the base.js asset file.
"""
cipher = Cipher(js=js)
for i, stream in enumerate(stream_manifest):
try:
url: str = stream["url"]
except KeyError:
live_stream = (
vid_info.get("playabilityStatus", {},)
.get("liveStreamability")
)
if live_stream:
raise LiveStreamError("UNKNOWN")
# 403 Forbidden fix.
if "signature" in url or (
"s" not in stream and ("&sig=" in url or "&lsig=" in url)
):
# For certain videos, YouTube will just provide them pre-signed, in
# which case there's no real magic to download them and we can skip
# the whole signature descrambling entirely.
logger.debug("signature found, skip decipher")
continue
signature = cipher.get_signature(ciphered_signature=stream["s"])
logger.debug(
"finished descrambling signature for itag=%s", stream["itag"]
)
parsed_url = urlparse(url)
# Convert query params off url to dict
query_params = parse_qs(urlparse(url).query)
query_params = {
k: v[0] for k,v in query_params.items()
}
query_params['sig'] = signature
if 'ratebypass' not in query_params.keys():
# Cipher n to get the updated value
initial_n = list(query_params['n'])
new_n = cipher.calculate_n(initial_n)
query_params['n'] = new_n
url = f'{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}?{urlencode(query_params)}' # noqa:E501
# 403 forbidden fix
stream_manifest[i]["url"] = url
|
Apply the decrypted signature to the stream manifest.
:param dict stream_manifest:
Details of the media streams available.
:param str js:
The contents of the base.js asset file.
|
apply_signature
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def apply_descrambler(stream_data: Dict) -> None:
"""Apply various in-place transforms to YouTube's media stream data.
Creates a ``list`` of dictionaries by string splitting on commas, then
taking each list item, parsing it as a query string, converting it to a
``dict`` and unquoting the value.
:param dict stream_data:
Dictionary containing query string encoded values.
**Example**:
>>> d = {'foo': 'bar=1&var=test,em=5&t=url%20encoded'}
>>> apply_descrambler(d, 'foo')
>>> print(d)
{'foo': [{'bar': '1', 'var': 'test'}, {'em': '5', 't': 'url encoded'}]}
"""
if 'url' in stream_data:
return None
# Merge formats and adaptiveFormats into a single list
formats = []
if 'formats' in stream_data.keys():
formats.extend(stream_data['formats'])
if 'adaptiveFormats' in stream_data.keys():
formats.extend(stream_data['adaptiveFormats'])
# Extract url and s from signatureCiphers as necessary
for data in formats:
if 'url' not in data:
if 'signatureCipher' in data:
cipher_url = parse_qs(data['signatureCipher'])
data['url'] = cipher_url['url'][0]
data['s'] = cipher_url['s'][0]
data['is_otf'] = data.get('type') == 'FORMAT_STREAM_TYPE_OTF'
logger.debug("applying descrambler")
return formats
|
Apply various in-place transforms to YouTube's media stream data.
Creates a ``list`` of dictionaries by string splitting on commas, then
taking each list item, parsing it as a query string, converting it to a
``dict`` and unquoting the value.
:param dict stream_data:
Dictionary containing query string encoded values.
**Example**:
>>> d = {'foo': 'bar=1&var=test,em=5&t=url%20encoded'}
>>> apply_descrambler(d, 'foo')
>>> print(d)
{'foo': [{'bar': '1', 'var': 'test'}, {'em': '5', 't': 'url encoded'}]}
|
apply_descrambler
|
python
|
pytube/pytube
|
pytube/extract.py
|
https://github.com/pytube/pytube/blob/master/pytube/extract.py
|
Unlicense
|
def __init__(self, generator):
"""Construct a :class:`DeferredGeneratorList <DeferredGeneratorList>`.
:param generator generator:
The deferrable generator to create a wrapper for.
:param func func:
(Optional) A function to call on the generator items to produce the list.
"""
self.gen = generator
self._elements = []
|
Construct a :class:`DeferredGeneratorList <DeferredGeneratorList>`.
:param generator generator:
The deferrable generator to create a wrapper for.
:param func func:
(Optional) A function to call on the generator items to produce the list.
|
__init__
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def __getitem__(self, key) -> Any:
"""Only generate items as they're asked for."""
# We only allow querying with indexes.
if not isinstance(key, (int, slice)):
raise TypeError('Key must be either a slice or int.')
# Convert int keys to slice
key_slice = key
if isinstance(key, int):
key_slice = slice(key, key + 1, 1)
# Generate all elements up to the final item
while len(self._elements) < key_slice.stop:
try:
next_item = next(self.gen)
except StopIteration:
# If we can't find enough elements for the slice, raise an IndexError
raise IndexError
else:
self._elements.append(next_item)
return self._elements[key]
|
Only generate items as they're asked for.
|
__getitem__
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def __iter__(self):
"""Custom iterator for dynamically generated list."""
iter_index = 0
while True:
try:
curr_item = self[iter_index]
except IndexError:
return
else:
yield curr_item
iter_index += 1
|
Custom iterator for dynamically generated list.
|
__iter__
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def regex_search(pattern: str, string: str, group: int) -> str:
"""Shortcut method to search a string for a given pattern.
:param str pattern:
A regular expression pattern.
:param str string:
A target string to search.
:param int group:
Index of group to return.
:rtype:
str or tuple
:returns:
Substring pattern matches.
"""
regex = re.compile(pattern)
results = regex.search(string)
if not results:
raise RegexMatchError(caller="regex_search", pattern=pattern)
logger.debug("matched regex search: %s", pattern)
return results.group(group)
|
Shortcut method to search a string for a given pattern.
:param str pattern:
A regular expression pattern.
:param str string:
A target string to search.
:param int group:
Index of group to return.
:rtype:
str or tuple
:returns:
Substring pattern matches.
|
regex_search
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def setup_logger(level: int = logging.ERROR, log_filename: Optional[str] = None) -> None:
"""Create a configured instance of logger.
:param int level:
Describe the severity level of the logs to handle.
"""
fmt = "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"
date_fmt = "%H:%M:%S"
formatter = logging.Formatter(fmt, datefmt=date_fmt)
# https://github.com/pytube/pytube/issues/163
logger = logging.getLogger("pytube")
logger.setLevel(level)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
if log_filename is not None:
file_handler = logging.FileHandler(log_filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
|
Create a configured instance of logger.
:param int level:
Describe the severity level of the logs to handle.
|
setup_logger
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def target_directory(output_path: Optional[str] = None) -> str:
"""
Function for determining target directory of a download.
Returns an absolute path (if relative one given) or the current
path (if none given). Makes directory if it does not exist.
:type output_path: str
:rtype: str
:returns:
An absolute directory path as a string.
"""
if output_path:
if not os.path.isabs(output_path):
output_path = os.path.join(os.getcwd(), output_path)
else:
output_path = os.getcwd()
os.makedirs(output_path, exist_ok=True)
return output_path
|
Function for determining target directory of a download.
Returns an absolute path (if relative one given) or the current
path (if none given). Makes directory if it does not exist.
:type output_path: str
:rtype: str
:returns:
An absolute directory path as a string.
|
target_directory
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def uniqueify(duped_list: List) -> List:
"""Remove duplicate items from a list, while maintaining list order.
:param List duped_list
List to remove duplicates from
:return List result
De-duplicated list
"""
seen: Dict[Any, bool] = {}
result = []
for item in duped_list:
if item in seen:
continue
seen[item] = True
result.append(item)
return result
|
Remove duplicate items from a list, while maintaining list order.
:param List duped_list
List to remove duplicates from
:return List result
De-duplicated list
|
uniqueify
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def generate_all_html_json_mocks():
"""Regenerate the video mock json files for all current test videos.
This should automatically output to the test/mocks directory.
"""
test_vid_ids = [
'2lAe1cqCOXo',
'5YceQ8YqYMc',
'irauhITDrsE',
'm8uHb5jIGN8',
'QRS8MkLhQmM',
'WXxV9g7lsFE'
]
for vid_id in test_vid_ids:
create_mock_html_json(vid_id)
|
Regenerate the video mock json files for all current test videos.
This should automatically output to the test/mocks directory.
|
generate_all_html_json_mocks
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def create_mock_html_json(vid_id) -> Dict[str, Any]:
"""Generate a json.gz file with sample html responses.
:param str vid_id
YouTube video id
:return dict data
Dict used to generate the json.gz file
"""
from pytube import YouTube
gzip_filename = 'yt-video-%s-html.json.gz' % vid_id
# Get the pytube directory in order to navigate to /tests/mocks
pytube_dir_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
os.path.pardir
)
)
pytube_mocks_path = os.path.join(pytube_dir_path, 'tests', 'mocks')
gzip_filepath = os.path.join(pytube_mocks_path, gzip_filename)
yt = YouTube(f'https://www.youtube.com/watch?v={vid_id}')
html_data = {
'url': yt.watch_url,
'js': yt.js,
'embed_html': yt.embed_html,
'watch_html': yt.watch_html,
'vid_info': yt.vid_info
}
logger.info(f'Outputing json.gz file to {gzip_filepath}')
with gzip.open(gzip_filepath, 'wb') as f:
f.write(json.dumps(html_data).encode('utf-8'))
return html_data
|
Generate a json.gz file with sample html responses.
:param str vid_id
YouTube video id
:return dict data
Dict used to generate the json.gz file
|
create_mock_html_json
|
python
|
pytube/pytube
|
pytube/helpers.py
|
https://github.com/pytube/pytube/blob/master/pytube/helpers.py
|
Unlicense
|
def __init__(self, client='ANDROID_MUSIC', use_oauth=False, allow_cache=True):
"""Initialize an InnerTube object.
:param str client:
Client to use for the object.
Default to web because it returns the most playback types.
:param bool use_oauth:
Whether or not to authenticate to YouTube.
:param bool allow_cache:
Allows caching of oauth tokens on the machine.
"""
self.context = _default_clients[client]['context']
self.header = _default_clients[client]['header']
self.api_key = _default_clients[client]['api_key']
self.access_token = None
self.refresh_token = None
self.use_oauth = use_oauth
self.allow_cache = allow_cache
# Stored as epoch time
self.expires = None
# Try to load from file if specified
if self.use_oauth and self.allow_cache:
# Try to load from file if possible
if os.path.exists(_token_file):
with open(_token_file) as f:
data = json.load(f)
self.access_token = data['access_token']
self.refresh_token = data['refresh_token']
self.expires = data['expires']
self.refresh_bearer_token()
|
Initialize an InnerTube object.
:param str client:
Client to use for the object.
Default to web because it returns the most playback types.
:param bool use_oauth:
Whether or not to authenticate to YouTube.
:param bool allow_cache:
Allows caching of oauth tokens on the machine.
|
__init__
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def cache_tokens(self):
"""Cache tokens to file if allowed."""
if not self.allow_cache:
return
data = {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'expires': self.expires
}
if not os.path.exists(_cache_dir):
os.mkdir(_cache_dir)
with open(_token_file, 'w') as f:
json.dump(data, f)
|
Cache tokens to file if allowed.
|
cache_tokens
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def refresh_bearer_token(self, force=False):
"""Refreshes the OAuth token if necessary.
:param bool force:
Force-refresh the bearer token.
"""
if not self.use_oauth:
return
# Skip refresh if it's not necessary and not forced
if self.expires > time.time() and not force:
return
# Subtracting 30 seconds is arbitrary to avoid potential time discrepencies
start_time = int(time.time() - 30)
data = {
'client_id': _client_id,
'client_secret': _client_secret,
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token
}
response = request._execute_request(
'https://oauth2.googleapis.com/token',
'POST',
headers={
'Content-Type': 'application/json'
},
data=data
)
response_data = json.loads(response.read())
self.access_token = response_data['access_token']
self.expires = start_time + response_data['expires_in']
self.cache_tokens()
|
Refreshes the OAuth token if necessary.
:param bool force:
Force-refresh the bearer token.
|
refresh_bearer_token
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def _call_api(self, endpoint, query, data):
"""Make a request to a given endpoint with the provided query parameters and data."""
# Remove the API key if oauth is being used.
if self.use_oauth:
del query['key']
endpoint_url = f'{endpoint}?{parse.urlencode(query)}'
headers = {
'Content-Type': 'application/json',
}
# Add the bearer token if applicable
if self.use_oauth:
if self.access_token:
self.refresh_bearer_token()
headers['Authorization'] = f'Bearer {self.access_token}'
else:
self.fetch_bearer_token()
headers['Authorization'] = f'Bearer {self.access_token}'
headers.update(self.header)
response = request._execute_request(
endpoint_url,
'POST',
headers=headers,
data=data
)
return json.loads(response.read())
|
Make a request to a given endpoint with the provided query parameters and data.
|
_call_api
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def browse(self):
"""Make a request to the browse endpoint.
TODO: Figure out how we can use this
"""
# endpoint = f'{self.base_url}/browse' # noqa:E800
...
# return self._call_api(endpoint, query, self.base_data) # noqa:E800
|
Make a request to the browse endpoint.
TODO: Figure out how we can use this
|
browse
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def config(self):
"""Make a request to the config endpoint.
TODO: Figure out how we can use this
"""
# endpoint = f'{self.base_url}/config' # noqa:E800
...
# return self._call_api(endpoint, query, self.base_data) # noqa:E800
|
Make a request to the config endpoint.
TODO: Figure out how we can use this
|
config
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def guide(self):
"""Make a request to the guide endpoint.
TODO: Figure out how we can use this
"""
# endpoint = f'{self.base_url}/guide' # noqa:E800
...
# return self._call_api(endpoint, query, self.base_data) # noqa:E800
|
Make a request to the guide endpoint.
TODO: Figure out how we can use this
|
guide
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def next(self):
"""Make a request to the next endpoint.
TODO: Figure out how we can use this
"""
# endpoint = f'{self.base_url}/next' # noqa:E800
...
# return self._call_api(endpoint, query, self.base_data) # noqa:E800
|
Make a request to the next endpoint.
TODO: Figure out how we can use this
|
next
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def player(self, video_id):
"""Make a request to the player endpoint.
:param str video_id:
The video id to get player info for.
:rtype: dict
:returns:
Raw player info results.
"""
endpoint = f'{self.base_url}/player'
query = {
'videoId': video_id,
}
query.update(self.base_params)
return self._call_api(endpoint, query, self.base_data)
|
Make a request to the player endpoint.
:param str video_id:
The video id to get player info for.
:rtype: dict
:returns:
Raw player info results.
|
player
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def search(self, search_query, continuation=None):
"""Make a request to the search endpoint.
:param str search_query:
The query to search.
:rtype: dict
:returns:
Raw search query results.
"""
endpoint = f'{self.base_url}/search'
query = {
'query': search_query
}
query.update(self.base_params)
data = {}
if continuation:
data['continuation'] = continuation
data.update(self.base_data)
return self._call_api(endpoint, query, data)
|
Make a request to the search endpoint.
:param str search_query:
The query to search.
:rtype: dict
:returns:
Raw search query results.
|
search
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def verify_age(self, video_id):
"""Make a request to the age_verify endpoint.
Notable examples of the types of video this verification step is for:
* https://www.youtube.com/watch?v=QLdAhwSBZ3w
* https://www.youtube.com/watch?v=hc0ZDaAZQT0
:param str video_id:
The video id to get player info for.
:rtype: dict
:returns:
Returns information that includes a URL for bypassing certain restrictions.
"""
endpoint = f'{self.base_url}/verify_age'
data = {
'nextEndpoint': {
'urlEndpoint': {
'url': f'/watch?v={video_id}'
}
},
'setControvercy': True
}
data.update(self.base_data)
result = self._call_api(endpoint, self.base_params, data)
return result
|
Make a request to the age_verify endpoint.
Notable examples of the types of video this verification step is for:
* https://www.youtube.com/watch?v=QLdAhwSBZ3w
* https://www.youtube.com/watch?v=hc0ZDaAZQT0
:param str video_id:
The video id to get player info for.
:rtype: dict
:returns:
Returns information that includes a URL for bypassing certain restrictions.
|
verify_age
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def get_transcript(self, video_id):
"""Make a request to the get_transcript endpoint.
This is likely related to captioning for videos, but is currently untested.
"""
endpoint = f'{self.base_url}/get_transcript'
query = {
'videoId': video_id,
}
query.update(self.base_params)
result = self._call_api(endpoint, query, self.base_data)
return result
|
Make a request to the get_transcript endpoint.
This is likely related to captioning for videos, but is currently untested.
|
get_transcript
|
python
|
pytube/pytube
|
pytube/innertube.py
|
https://github.com/pytube/pytube/blob/master/pytube/innertube.py
|
Unlicense
|
def get_format_profile(itag: int) -> Dict:
"""Get additional format information for a given itag.
:param str itag:
YouTube format identifier code.
"""
itag = int(itag)
if itag in ITAGS:
res, bitrate = ITAGS[itag]
else:
res, bitrate = None, None
return {
"resolution": res,
"abr": bitrate,
"is_live": itag in LIVE,
"is_3d": itag in _3D,
"is_hdr": itag in HDR,
"is_dash": (
itag in DASH_AUDIO
or itag in DASH_VIDEO
),
}
|
Get additional format information for a given itag.
:param str itag:
YouTube format identifier code.
|
get_format_profile
|
python
|
pytube/pytube
|
pytube/itags.py
|
https://github.com/pytube/pytube/blob/master/pytube/itags.py
|
Unlicense
|
def parse_for_all_objects(html, preceding_regex):
"""Parses input html to find all matches for the input starting point.
:param str html:
HTML to be parsed for an object.
:param str preceding_regex:
Regex to find the string preceding the object.
:rtype list:
:returns:
A list of dicts created from parsing the objects.
"""
result = []
regex = re.compile(preceding_regex)
match_iter = regex.finditer(html)
for match in match_iter:
if match:
start_index = match.end()
try:
obj = parse_for_object_from_startpoint(html, start_index)
except HTMLParseError:
# Some of the instances might fail because set is technically
# a method of the ytcfg object. We'll skip these since they
# don't seem relevant at the moment.
continue
else:
result.append(obj)
if len(result) == 0:
raise HTMLParseError(f'No matches for regex {preceding_regex}')
return result
|
Parses input html to find all matches for the input starting point.
:param str html:
HTML to be parsed for an object.
:param str preceding_regex:
Regex to find the string preceding the object.
:rtype list:
:returns:
A list of dicts created from parsing the objects.
|
parse_for_all_objects
|
python
|
pytube/pytube
|
pytube/parser.py
|
https://github.com/pytube/pytube/blob/master/pytube/parser.py
|
Unlicense
|
def parse_for_object(html, preceding_regex):
"""Parses input html to find the end of a JavaScript object.
:param str html:
HTML to be parsed for an object.
:param str preceding_regex:
Regex to find the string preceding the object.
:rtype dict:
:returns:
A dict created from parsing the object.
"""
regex = re.compile(preceding_regex)
result = regex.search(html)
if not result:
raise HTMLParseError(f'No matches for regex {preceding_regex}')
start_index = result.end()
return parse_for_object_from_startpoint(html, start_index)
|
Parses input html to find the end of a JavaScript object.
:param str html:
HTML to be parsed for an object.
:param str preceding_regex:
Regex to find the string preceding the object.
:rtype dict:
:returns:
A dict created from parsing the object.
|
parse_for_object
|
python
|
pytube/pytube
|
pytube/parser.py
|
https://github.com/pytube/pytube/blob/master/pytube/parser.py
|
Unlicense
|
def find_object_from_startpoint(html, start_point):
"""Parses input html to find the end of a JavaScript object.
:param str html:
HTML to be parsed for an object.
:param int start_point:
Index of where the object starts.
:rtype dict:
:returns:
A dict created from parsing the object.
"""
html = html[start_point:]
if html[0] not in ['{','[']:
raise HTMLParseError(f'Invalid start point. Start of HTML:\n{html[:20]}')
# First letter MUST be a open brace, so we put that in the stack,
# and skip the first character.
last_char = '{'
curr_char = None
stack = [html[0]]
i = 1
context_closers = {
'{': '}',
'[': ']',
'"': '"',
'/': '/' # javascript regex
}
while i < len(html):
if len(stack) == 0:
break
if curr_char not in [' ', '\n']:
last_char = curr_char
curr_char = html[i]
curr_context = stack[-1]
# If we've reached a context closer, we can remove an element off the stack
if curr_char == context_closers[curr_context]:
stack.pop()
i += 1
continue
# Strings and regex expressions require special context handling because they can contain
# context openers *and* closers
if curr_context in ['"', '/']:
# If there's a backslash in a string or regex expression, we skip a character
if curr_char == '\\':
i += 2
continue
else:
# Non-string contexts are when we need to look for context openers.
if curr_char in context_closers.keys():
# Slash starts a regular expression depending on context
if not (curr_char == '/' and last_char not in ['(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';']):
stack.append(curr_char)
i += 1
full_obj = html[:i]
return full_obj # noqa: R504
|
Parses input html to find the end of a JavaScript object.
:param str html:
HTML to be parsed for an object.
:param int start_point:
Index of where the object starts.
:rtype dict:
:returns:
A dict created from parsing the object.
|
find_object_from_startpoint
|
python
|
pytube/pytube
|
pytube/parser.py
|
https://github.com/pytube/pytube/blob/master/pytube/parser.py
|
Unlicense
|
def parse_for_object_from_startpoint(html, start_point):
"""JSONifies an object parsed from HTML.
:param str html:
HTML to be parsed for an object.
:param int start_point:
Index of where the object starts.
:rtype dict:
:returns:
A dict created from parsing the object.
"""
full_obj = find_object_from_startpoint(html, start_point)
try:
return json.loads(full_obj)
except json.decoder.JSONDecodeError:
try:
return ast.literal_eval(full_obj)
except (ValueError, SyntaxError):
raise HTMLParseError('Could not parse object.')
|
JSONifies an object parsed from HTML.
:param str html:
HTML to be parsed for an object.
:param int start_point:
Index of where the object starts.
:rtype dict:
:returns:
A dict created from parsing the object.
|
parse_for_object_from_startpoint
|
python
|
pytube/pytube
|
pytube/parser.py
|
https://github.com/pytube/pytube/blob/master/pytube/parser.py
|
Unlicense
|
def throttling_array_split(js_array):
"""Parses the throttling array into a python list of strings.
Expects input to begin with `[` and close with `]`.
:param str js_array:
The javascript array, as a string.
:rtype: list:
:returns:
A list of strings representing splits on `,` in the throttling array.
"""
results = []
curr_substring = js_array[1:]
comma_regex = re.compile(r",")
func_regex = re.compile(r"function\([^)]*\)")
while len(curr_substring) > 0:
if curr_substring.startswith('function'):
# Handle functions separately. These can contain commas
match = func_regex.search(curr_substring)
match_start, match_end = match.span()
function_text = find_object_from_startpoint(curr_substring, match.span()[1])
full_function_def = curr_substring[:match_end + len(function_text)]
results.append(full_function_def)
curr_substring = curr_substring[len(full_function_def) + 1:]
else:
match = comma_regex.search(curr_substring)
# Try-catch to capture end of array
try:
match_start, match_end = match.span()
except AttributeError:
match_start = len(curr_substring) - 1
match_end = match_start + 1
curr_el = curr_substring[:match_start]
results.append(curr_el)
curr_substring = curr_substring[match_end:]
return results
|
Parses the throttling array into a python list of strings.
Expects input to begin with `[` and close with `]`.
:param str js_array:
The javascript array, as a string.
:rtype: list:
:returns:
A list of strings representing splits on `,` in the throttling array.
|
throttling_array_split
|
python
|
pytube/pytube
|
pytube/parser.py
|
https://github.com/pytube/pytube/blob/master/pytube/parser.py
|
Unlicense
|
def __init__(self, fmt_streams):
"""Construct a :class:`StreamQuery <StreamQuery>`.
param list fmt_streams:
list of :class:`Stream <Stream>` instances.
"""
self.fmt_streams = fmt_streams
self.itag_index = {int(s.itag): s for s in fmt_streams}
|
Construct a :class:`StreamQuery <StreamQuery>`.
param list fmt_streams:
list of :class:`Stream <Stream>` instances.
|
__init__
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def filter(
self,
fps=None,
res=None,
resolution=None,
mime_type=None,
type=None,
subtype=None,
file_extension=None,
abr=None,
bitrate=None,
video_codec=None,
audio_codec=None,
only_audio=None,
only_video=None,
progressive=None,
adaptive=None,
is_dash=None,
custom_filter_functions=None,
):
"""Apply the given filtering criterion.
:param fps:
(optional) The frames per second.
:type fps:
int or None
:param resolution:
(optional) Alias to ``res``.
:type res:
str or None
:param res:
(optional) The video resolution.
:type resolution:
str or None
:param mime_type:
(optional) Two-part identifier for file formats and format contents
composed of a "type", a "subtype".
:type mime_type:
str or None
:param type:
(optional) Type part of the ``mime_type`` (e.g.: audio, video).
:type type:
str or None
:param subtype:
(optional) Sub-type part of the ``mime_type`` (e.g.: mp4, mov).
:type subtype:
str or None
:param file_extension:
(optional) Alias to ``sub_type``.
:type file_extension:
str or None
:param abr:
(optional) Average bitrate (ABR) refers to the average amount of
data transferred per unit of time (e.g.: 64kbps, 192kbps).
:type abr:
str or None
:param bitrate:
(optional) Alias to ``abr``.
:type bitrate:
str or None
:param video_codec:
(optional) Video compression format.
:type video_codec:
str or None
:param audio_codec:
(optional) Audio compression format.
:type audio_codec:
str or None
:param bool progressive:
Excludes adaptive streams (one file contains both audio and video
tracks).
:param bool adaptive:
Excludes progressive streams (audio and video are on separate
tracks).
:param bool is_dash:
Include/exclude dash streams.
:param bool only_audio:
Excludes streams with video tracks.
:param bool only_video:
Excludes streams with audio tracks.
:param custom_filter_functions:
(optional) Interface for defining complex filters without
subclassing.
:type custom_filter_functions:
list or None
"""
filters = []
if res or resolution:
if isinstance(res, str) or isinstance(resolution, str):
filters.append(lambda s: s.resolution == (res or resolution))
elif isinstance(res, list) or isinstance(resolution, list):
filters.append(lambda s: s.resolution in (res or resolution))
if fps:
filters.append(lambda s: s.fps == fps)
if mime_type:
filters.append(lambda s: s.mime_type == mime_type)
if type:
filters.append(lambda s: s.type == type)
if subtype or file_extension:
filters.append(lambda s: s.subtype == (subtype or file_extension))
if abr or bitrate:
filters.append(lambda s: s.abr == (abr or bitrate))
if video_codec:
filters.append(lambda s: s.video_codec == video_codec)
if audio_codec:
filters.append(lambda s: s.audio_codec == audio_codec)
if only_audio:
filters.append(
lambda s: (
s.includes_audio_track and not s.includes_video_track
),
)
if only_video:
filters.append(
lambda s: (
s.includes_video_track and not s.includes_audio_track
),
)
if progressive:
filters.append(lambda s: s.is_progressive)
if adaptive:
filters.append(lambda s: s.is_adaptive)
if custom_filter_functions:
filters.extend(custom_filter_functions)
if is_dash is not None:
filters.append(lambda s: s.is_dash == is_dash)
return self._filter(filters)
|
Apply the given filtering criterion.
:param fps:
(optional) The frames per second.
:type fps:
int or None
:param resolution:
(optional) Alias to ``res``.
:type res:
str or None
:param res:
(optional) The video resolution.
:type resolution:
str or None
:param mime_type:
(optional) Two-part identifier for file formats and format contents
composed of a "type", a "subtype".
:type mime_type:
str or None
:param type:
(optional) Type part of the ``mime_type`` (e.g.: audio, video).
:type type:
str or None
:param subtype:
(optional) Sub-type part of the ``mime_type`` (e.g.: mp4, mov).
:type subtype:
str or None
:param file_extension:
(optional) Alias to ``sub_type``.
:type file_extension:
str or None
:param abr:
(optional) Average bitrate (ABR) refers to the average amount of
data transferred per unit of time (e.g.: 64kbps, 192kbps).
:type abr:
str or None
:param bitrate:
(optional) Alias to ``abr``.
:type bitrate:
str or None
:param video_codec:
(optional) Video compression format.
:type video_codec:
str or None
:param audio_codec:
(optional) Audio compression format.
:type audio_codec:
str or None
:param bool progressive:
Excludes adaptive streams (one file contains both audio and video
tracks).
:param bool adaptive:
Excludes progressive streams (audio and video are on separate
tracks).
:param bool is_dash:
Include/exclude dash streams.
:param bool only_audio:
Excludes streams with video tracks.
:param bool only_video:
Excludes streams with audio tracks.
:param custom_filter_functions:
(optional) Interface for defining complex filters without
subclassing.
:type custom_filter_functions:
list or None
|
filter
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def order_by(self, attribute_name: str) -> "StreamQuery":
"""Apply a sort order. Filters out stream the do not have the attribute.
:param str attribute_name:
The name of the attribute to sort by.
"""
has_attribute = [
s
for s in self.fmt_streams
if getattr(s, attribute_name) is not None
]
# Check that the attributes have string values.
if has_attribute and isinstance(
getattr(has_attribute[0], attribute_name), str
):
# Try to return a StreamQuery sorted by the integer representations
# of the values.
try:
return StreamQuery(
sorted(
has_attribute,
key=lambda s: int(
"".join(
filter(str.isdigit, getattr(s, attribute_name))
)
), # type: ignore # noqa: E501
)
)
except ValueError:
pass
return StreamQuery(
sorted(has_attribute, key=lambda s: getattr(s, attribute_name))
)
|
Apply a sort order. Filters out stream the do not have the attribute.
:param str attribute_name:
The name of the attribute to sort by.
|
order_by
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def get_by_resolution(self, resolution: str) -> Optional[Stream]:
"""Get the corresponding :class:`Stream <Stream>` for a given resolution.
Stream must be a progressive mp4.
:param str resolution:
Video resolution i.e. "720p", "480p", "360p", "240p", "144p"
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
"""
return self.filter(
progressive=True, subtype="mp4", resolution=resolution
).first()
|
Get the corresponding :class:`Stream <Stream>` for a given resolution.
Stream must be a progressive mp4.
:param str resolution:
Video resolution i.e. "720p", "480p", "360p", "240p", "144p"
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
|
get_by_resolution
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def get_lowest_resolution(self) -> Optional[Stream]:
"""Get lowest resolution stream that is a progressive mp4.
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
"""
return (
self.filter(progressive=True, subtype="mp4")
.order_by("resolution")
.first()
)
|
Get lowest resolution stream that is a progressive mp4.
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
|
get_lowest_resolution
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def get_audio_only(self, subtype: str = "mp4") -> Optional[Stream]:
"""Get highest bitrate audio stream for given codec (defaults to mp4)
:param str subtype:
Audio subtype, defaults to mp4
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
"""
return (
self.filter(only_audio=True, subtype=subtype)
.order_by("abr")
.last()
)
|
Get highest bitrate audio stream for given codec (defaults to mp4)
:param str subtype:
Audio subtype, defaults to mp4
:rtype: :class:`Stream <Stream>` or None
:returns:
The :class:`Stream <Stream>` matching the given itag or None if
not found.
|
get_audio_only
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def first(self) -> Optional[Stream]:
"""Get the first :class:`Stream <Stream>` in the results.
:rtype: :class:`Stream <Stream>` or None
:returns:
the first result of this query or None if the result doesn't
contain any streams.
"""
try:
return self.fmt_streams[0]
except IndexError:
return None
|
Get the first :class:`Stream <Stream>` in the results.
:rtype: :class:`Stream <Stream>` or None
:returns:
the first result of this query or None if the result doesn't
contain any streams.
|
first
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def last(self):
"""Get the last :class:`Stream <Stream>` in the results.
:rtype: :class:`Stream <Stream>` or None
:returns:
Return the last result of this query or None if the result
doesn't contain any streams.
"""
try:
return self.fmt_streams[-1]
except IndexError:
pass
|
Get the last :class:`Stream <Stream>` in the results.
:rtype: :class:`Stream <Stream>` or None
:returns:
Return the last result of this query or None if the result
doesn't contain any streams.
|
last
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def count(self, value: Optional[str] = None) -> int: # pragma: no cover
"""Get the count of items in the list.
:rtype: int
"""
if value:
return self.fmt_streams.count(value)
return len(self)
|
Get the count of items in the list.
:rtype: int
|
count
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def get_by_language_code(
self, lang_code: str
) -> Optional[Caption]: # pragma: no cover
"""Get the :class:`Caption <Caption>` for a given ``lang_code``.
:param str lang_code:
The code that identifies the caption language.
:rtype: :class:`Caption <Caption>` or None
:returns:
The :class:`Caption <Caption>` matching the given ``lang_code`` or
None if it does not exist.
"""
return self.lang_code_index.get(lang_code)
|
Get the :class:`Caption <Caption>` for a given ``lang_code``.
:param str lang_code:
The code that identifies the caption language.
:rtype: :class:`Caption <Caption>` or None
:returns:
The :class:`Caption <Caption>` matching the given ``lang_code`` or
None if it does not exist.
|
get_by_language_code
|
python
|
pytube/pytube
|
pytube/query.py
|
https://github.com/pytube/pytube/blob/master/pytube/query.py
|
Unlicense
|
def get(url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
"""Send an http GET request.
:param str url:
The URL to perform the GET request for.
:param dict extra_headers:
Extra headers to add to the request
:rtype: str
:returns:
UTF-8 encoded string of response
"""
if extra_headers is None:
extra_headers = {}
response = _execute_request(url, headers=extra_headers, timeout=timeout)
return response.read().decode("utf-8")
|
Send an http GET request.
:param str url:
The URL to perform the GET request for.
:param dict extra_headers:
Extra headers to add to the request
:rtype: str
:returns:
UTF-8 encoded string of response
|
get
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def post(url, extra_headers=None, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
"""Send an http POST request.
:param str url:
The URL to perform the POST request for.
:param dict extra_headers:
Extra headers to add to the request
:param dict data:
The data to send on the POST request
:rtype: str
:returns:
UTF-8 encoded string of response
"""
# could technically be implemented in get,
# but to avoid confusion implemented like this
if extra_headers is None:
extra_headers = {}
if data is None:
data = {}
# required because the youtube servers are strict on content type
# raises HTTPError [400]: Bad Request otherwise
extra_headers.update({"Content-Type": "application/json"})
response = _execute_request(
url,
headers=extra_headers,
data=data,
timeout=timeout
)
return response.read().decode("utf-8")
|
Send an http POST request.
:param str url:
The URL to perform the POST request for.
:param dict extra_headers:
Extra headers to add to the request
:param dict data:
The data to send on the POST request
:rtype: str
:returns:
UTF-8 encoded string of response
|
post
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def seq_stream(
url,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
max_retries=0
):
"""Read the response in sequence.
:param str url: The URL to perform the GET request for.
:rtype: Iterable[bytes]
"""
# YouTube expects a request sequence number as part of the parameters.
split_url = parse.urlsplit(url)
base_url = '%s://%s/%s?' % (split_url.scheme, split_url.netloc, split_url.path)
querys = dict(parse.parse_qsl(split_url.query))
# The 0th sequential request provides the file headers, which tell us
# information about how the file is segmented.
querys['sq'] = 0
url = base_url + parse.urlencode(querys)
segment_data = b''
for chunk in stream(url, timeout=timeout, max_retries=max_retries):
yield chunk
segment_data += chunk
# We can then parse the header to find the number of segments
stream_info = segment_data.split(b'\r\n')
segment_count_pattern = re.compile(b'Segment-Count: (\\d+)')
for line in stream_info:
match = segment_count_pattern.search(line)
if match:
segment_count = int(match.group(1).decode('utf-8'))
# We request these segments sequentially to build the file.
seq_num = 1
while seq_num <= segment_count:
# Create sequential request URL
querys['sq'] = seq_num
url = base_url + parse.urlencode(querys)
yield from stream(url, timeout=timeout, max_retries=max_retries)
seq_num += 1
return # pylint: disable=R1711
|
Read the response in sequence.
:param str url: The URL to perform the GET request for.
:rtype: Iterable[bytes]
|
seq_stream
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def stream(
url,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
max_retries=0
):
"""Read the response in chunks.
:param str url: The URL to perform the GET request for.
:rtype: Iterable[bytes]
"""
file_size: int = default_range_size # fake filesize to start
downloaded = 0
while downloaded < file_size:
stop_pos = min(downloaded + default_range_size, file_size) - 1
range_header = f"bytes={downloaded}-{stop_pos}"
tries = 0
# Attempt to make the request multiple times as necessary.
while True:
# If the max retries is exceeded, raise an exception
if tries >= 1 + max_retries:
raise MaxRetriesExceeded()
# Try to execute the request, ignoring socket timeouts
try:
response = _execute_request(
url + f"&range={downloaded}-{stop_pos}",
method="GET",
timeout=timeout
)
except URLError as e:
# We only want to skip over timeout errors, and
# raise any other URLError exceptions
if isinstance(e.reason, socket.timeout):
pass
else:
raise
except http.client.IncompleteRead:
# Allow retries on IncompleteRead errors for unreliable connections
pass
else:
# On a successful request, break from loop
break
tries += 1
if file_size == default_range_size:
try:
resp = _execute_request(
url + f"&range={0}-{99999999999}",
method="GET",
timeout=timeout
)
content_range = resp.info()["Content-Length"]
file_size = int(content_range)
except (KeyError, IndexError, ValueError) as e:
logger.error(e)
while True:
chunk = response.read()
if not chunk:
break
downloaded += len(chunk)
yield chunk
return # pylint: disable=R1711
|
Read the response in chunks.
:param str url: The URL to perform the GET request for.
:rtype: Iterable[bytes]
|
stream
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def seq_filesize(url):
"""Fetch size in bytes of file at given URL from sequential requests
:param str url: The URL to get the size of
:returns: int: size in bytes of remote file
"""
total_filesize = 0
# YouTube expects a request sequence number as part of the parameters.
split_url = parse.urlsplit(url)
base_url = '%s://%s/%s?' % (split_url.scheme, split_url.netloc, split_url.path)
querys = dict(parse.parse_qsl(split_url.query))
# The 0th sequential request provides the file headers, which tell us
# information about how the file is segmented.
querys['sq'] = 0
url = base_url + parse.urlencode(querys)
response = _execute_request(
url, method="GET"
)
response_value = response.read()
# The file header must be added to the total filesize
total_filesize += len(response_value)
# We can then parse the header to find the number of segments
segment_count = 0
stream_info = response_value.split(b'\r\n')
segment_regex = b'Segment-Count: (\\d+)'
for line in stream_info:
# One of the lines should contain the segment count, but we don't know
# which, so we need to iterate through the lines to find it
try:
segment_count = int(regex_search(segment_regex, line, 1))
except RegexMatchError:
pass
if segment_count == 0:
raise RegexMatchError('seq_filesize', segment_regex)
# We make HEAD requests to the segments sequentially to find the total filesize.
seq_num = 1
while seq_num <= segment_count:
# Create sequential request URL
querys['sq'] = seq_num
url = base_url + parse.urlencode(querys)
total_filesize += int(head(url)['content-length'])
seq_num += 1
return total_filesize
|
Fetch size in bytes of file at given URL from sequential requests
:param str url: The URL to get the size of
:returns: int: size in bytes of remote file
|
seq_filesize
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def head(url):
"""Fetch headers returned http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: dict
:returns:
dictionary of lowercase headers
"""
response_headers = _execute_request(url, method="HEAD").info()
return {k.lower(): v for k, v in response_headers.items()}
|
Fetch headers returned http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: dict
:returns:
dictionary of lowercase headers
|
head
|
python
|
pytube/pytube
|
pytube/request.py
|
https://github.com/pytube/pytube/blob/master/pytube/request.py
|
Unlicense
|
def __init__(
self, stream: Dict, monostate: Monostate
):
"""Construct a :class:`Stream <Stream>`.
:param dict stream:
The unscrambled data extracted from YouTube.
:param dict monostate:
Dictionary of data shared across all instances of
:class:`Stream <Stream>`.
"""
# A dictionary shared between all instances of :class:`Stream <Stream>`
# (Borg pattern).
self._monostate = monostate
self.url = stream["url"] # signed download url
self.itag = int(
stream["itag"]
) # stream format id (youtube nomenclature)
# set type and codec info
# 'video/webm; codecs="vp8, vorbis"' -> 'video/webm', ['vp8', 'vorbis']
self.mime_type, self.codecs = extract.mime_type_codec(stream["mimeType"])
# 'video/webm' -> 'video', 'webm'
self.type, self.subtype = self.mime_type.split("/")
# ['vp8', 'vorbis'] -> video_codec: vp8, audio_codec: vorbis. DASH
# streams return NoneType for audio/video depending.
self.video_codec, self.audio_codec = self.parse_codecs()
self.is_otf: bool = stream["is_otf"]
self.bitrate: Optional[int] = stream["bitrate"]
# filesize in bytes
self._filesize: Optional[int] = int(stream.get('contentLength', 0))
# filesize in kilobytes
self._filesize_kb: Optional[float] = float(ceil(float(stream.get('contentLength', 0)) / 1024 * 1000) / 1000)
# filesize in megabytes
self._filesize_mb: Optional[float] = float(ceil(float(stream.get('contentLength', 0)) / 1024 / 1024 * 1000) / 1000)
# filesize in gigabytes(fingers crossed we don't need terabytes going forward though)
self._filesize_gb: Optional[float] = float(ceil(float(stream.get('contentLength', 0)) / 1024 / 1024 / 1024 * 1000) / 1000)
# Additional information about the stream format, such as resolution,
# frame rate, and whether the stream is live (HLS) or 3D.
itag_profile = get_format_profile(self.itag)
self.is_dash = itag_profile["is_dash"]
self.abr = itag_profile["abr"] # average bitrate (audio streams only)
if 'fps' in stream:
self.fps = stream['fps'] # Video streams only
self.resolution = itag_profile[
"resolution"
] # resolution (e.g.: "480p")
self.is_3d = itag_profile["is_3d"]
self.is_hdr = itag_profile["is_hdr"]
self.is_live = itag_profile["is_live"]
|
Construct a :class:`Stream <Stream>`.
:param dict stream:
The unscrambled data extracted from YouTube.
:param dict monostate:
Dictionary of data shared across all instances of
:class:`Stream <Stream>`.
|
__init__
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def is_adaptive(self) -> bool:
"""Whether the stream is DASH.
:rtype: bool
"""
# if codecs has two elements (e.g.: ['vp8', 'vorbis']): 2 % 2 = 0
# if codecs has one element (e.g.: ['vp8']) 1 % 2 = 1
return bool(len(self.codecs) % 2)
|
Whether the stream is DASH.
:rtype: bool
|
is_adaptive
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def parse_codecs(self) -> Tuple[Optional[str], Optional[str]]:
"""Get the video/audio codecs from list of codecs.
Parse a variable length sized list of codecs and returns a
constant two element tuple, with the video codec as the first element
and audio as the second. Returns None if one is not available
(adaptive only).
:rtype: tuple
:returns:
A two element tuple with audio and video codecs.
"""
video = None
audio = None
if not self.is_adaptive:
video, audio = self.codecs
elif self.includes_video_track:
video = self.codecs[0]
elif self.includes_audio_track:
audio = self.codecs[0]
return video, audio
|
Get the video/audio codecs from list of codecs.
Parse a variable length sized list of codecs and returns a
constant two element tuple, with the video codec as the first element
and audio as the second. Returns None if one is not available
(adaptive only).
:rtype: tuple
:returns:
A two element tuple with audio and video codecs.
|
parse_codecs
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def filesize(self) -> int:
"""File size of the media stream in bytes.
:rtype: int
:returns:
Filesize (in bytes) of the stream.
"""
if self._filesize == 0:
try:
self._filesize = request.filesize(self.url)
except HTTPError as e:
if e.code != 404:
raise
self._filesize = request.seq_filesize(self.url)
return self._filesize
|
File size of the media stream in bytes.
:rtype: int
:returns:
Filesize (in bytes) of the stream.
|
filesize
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def filesize_kb(self) -> float:
"""File size of the media stream in kilobytes.
:rtype: float
:returns:
Rounded filesize (in kilobytes) of the stream.
"""
if self._filesize_kb == 0:
try:
self._filesize_kb = float(ceil(request.filesize(self.url)/1024 * 1000) / 1000)
except HTTPError as e:
if e.code != 404:
raise
self._filesize_kb = float(ceil(request.seq_filesize(self.url)/1024 * 1000) / 1000)
return self._filesize_kb
|
File size of the media stream in kilobytes.
:rtype: float
:returns:
Rounded filesize (in kilobytes) of the stream.
|
filesize_kb
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def filesize_mb(self) -> float:
"""File size of the media stream in megabytes.
:rtype: float
:returns:
Rounded filesize (in megabytes) of the stream.
"""
if self._filesize_mb == 0:
try:
self._filesize_mb = float(ceil(request.filesize(self.url)/1024/1024 * 1000) / 1000)
except HTTPError as e:
if e.code != 404:
raise
self._filesize_mb = float(ceil(request.seq_filesize(self.url)/1024/1024 * 1000) / 1000)
return self._filesize_mb
|
File size of the media stream in megabytes.
:rtype: float
:returns:
Rounded filesize (in megabytes) of the stream.
|
filesize_mb
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def filesize_gb(self) -> float:
"""File size of the media stream in gigabytes.
:rtype: float
:returns:
Rounded filesize (in gigabytes) of the stream.
"""
if self._filesize_gb == 0:
try:
self._filesize_gb = float(ceil(request.filesize(self.url)/1024/1024/1024 * 1000) / 1000)
except HTTPError as e:
if e.code != 404:
raise
self._filesize_gb = float(ceil(request.seq_filesize(self.url)/1024/1024/1024 * 1000) / 1000)
return self._filesize_gb
|
File size of the media stream in gigabytes.
:rtype: float
:returns:
Rounded filesize (in gigabytes) of the stream.
|
filesize_gb
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def filesize_approx(self) -> int:
"""Get approximate filesize of the video
Falls back to HTTP call if there is not sufficient information to approximate
:rtype: int
:returns: size of video in bytes
"""
if self._monostate.duration and self.bitrate:
bits_in_byte = 8
return int(
(self._monostate.duration * self.bitrate) / bits_in_byte
)
return self.filesize
|
Get approximate filesize of the video
Falls back to HTTP call if there is not sufficient information to approximate
:rtype: int
:returns: size of video in bytes
|
filesize_approx
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def download(
self,
output_path: Optional[str] = None,
filename: Optional[str] = None,
filename_prefix: Optional[str] = None,
skip_existing: bool = True,
timeout: Optional[int] = None,
max_retries: Optional[int] = 0
) -> str:
"""Write the media stream to disk.
:param output_path:
(optional) Output path for writing media file. If one is not
specified, defaults to the current working directory.
:type output_path: str or None
:param filename:
(optional) Output filename (stem only) for writing media file.
If one is not specified, the default filename is used.
:type filename: str or None
:param filename_prefix:
(optional) A string that will be prepended to the filename.
For example a number in a playlist or the name of a series.
If one is not specified, nothing will be prepended
This is separate from filename so you can use the default
filename but still add a prefix.
:type filename_prefix: str or None
:param skip_existing:
(optional) Skip existing files, defaults to True
:type skip_existing: bool
:param timeout:
(optional) Request timeout length in seconds. Uses system default.
:type timeout: int
:param max_retries:
(optional) Number of retries to attempt after socket timeout. Defaults to 0.
:type max_retries: int
:returns:
Path to the saved video
:rtype: str
"""
file_path = self.get_file_path(
filename=filename,
output_path=output_path,
filename_prefix=filename_prefix,
)
if skip_existing and self.exists_at_path(file_path):
logger.debug(f'file {file_path} already exists, skipping')
self.on_complete(file_path)
return file_path
bytes_remaining = self.filesize
logger.debug(f'downloading ({self.filesize} total bytes) file to {file_path}')
with open(file_path, "wb") as fh:
try:
for chunk in request.stream(
self.url,
timeout=timeout,
max_retries=max_retries
):
# reduce the (bytes) remainder by the length of the chunk.
bytes_remaining -= len(chunk)
# send to the on_progress callback.
self.on_progress(chunk, fh, bytes_remaining)
except HTTPError as e:
if e.code != 404:
raise
# Some adaptive streams need to be requested with sequence numbers
for chunk in request.seq_stream(
self.url,
timeout=timeout,
max_retries=max_retries
):
# reduce the (bytes) remainder by the length of the chunk.
bytes_remaining -= len(chunk)
# send to the on_progress callback.
self.on_progress(chunk, fh, bytes_remaining)
self.on_complete(file_path)
return file_path
|
Write the media stream to disk.
:param output_path:
(optional) Output path for writing media file. If one is not
specified, defaults to the current working directory.
:type output_path: str or None
:param filename:
(optional) Output filename (stem only) for writing media file.
If one is not specified, the default filename is used.
:type filename: str or None
:param filename_prefix:
(optional) A string that will be prepended to the filename.
For example a number in a playlist or the name of a series.
If one is not specified, nothing will be prepended
This is separate from filename so you can use the default
filename but still add a prefix.
:type filename_prefix: str or None
:param skip_existing:
(optional) Skip existing files, defaults to True
:type skip_existing: bool
:param timeout:
(optional) Request timeout length in seconds. Uses system default.
:type timeout: int
:param max_retries:
(optional) Number of retries to attempt after socket timeout. Defaults to 0.
:type max_retries: int
:returns:
Path to the saved video
:rtype: str
|
download
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def stream_to_buffer(self, buffer: BinaryIO) -> None:
"""Write the media stream to buffer
:rtype: io.BytesIO buffer
"""
bytes_remaining = self.filesize
logger.info(
"downloading (%s total bytes) file to buffer", self.filesize,
)
for chunk in request.stream(self.url):
# reduce the (bytes) remainder by the length of the chunk.
bytes_remaining -= len(chunk)
# send to the on_progress callback.
self.on_progress(chunk, buffer, bytes_remaining)
self.on_complete(None)
|
Write the media stream to buffer
:rtype: io.BytesIO buffer
|
stream_to_buffer
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def on_progress(
self, chunk: bytes, file_handler: BinaryIO, bytes_remaining: int
):
"""On progress callback function.
This function writes the binary data to the file, then checks if an
additional callback is defined in the monostate. This is exposed to
allow things like displaying a progress bar.
:param bytes chunk:
Segment of media file binary data, not yet written to disk.
:param file_handler:
The file handle where the media is being written to.
:type file_handler:
:py:class:`io.BufferedWriter`
:param int bytes_remaining:
The delta between the total file size in bytes and amount already
downloaded.
:rtype: None
"""
file_handler.write(chunk)
logger.debug("download remaining: %s", bytes_remaining)
if self._monostate.on_progress:
self._monostate.on_progress(self, chunk, bytes_remaining)
|
On progress callback function.
This function writes the binary data to the file, then checks if an
additional callback is defined in the monostate. This is exposed to
allow things like displaying a progress bar.
:param bytes chunk:
Segment of media file binary data, not yet written to disk.
:param file_handler:
The file handle where the media is being written to.
:type file_handler:
:py:class:`io.BufferedWriter`
:param int bytes_remaining:
The delta between the total file size in bytes and amount already
downloaded.
:rtype: None
|
on_progress
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def on_complete(self, file_path: Optional[str]):
"""On download complete handler function.
:param file_path:
The file handle where the media is being written to.
:type file_path: str
:rtype: None
"""
logger.debug("download finished")
on_complete = self._monostate.on_complete
if on_complete:
logger.debug("calling on_complete callback %s", on_complete)
on_complete(self, file_path)
|
On download complete handler function.
:param file_path:
The file handle where the media is being written to.
:type file_path: str
:rtype: None
|
on_complete
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def __repr__(self) -> str:
"""Printable object representation.
:rtype: str
:returns:
A string representation of a :class:`Stream <Stream>` object.
"""
parts = ['itag="{s.itag}"', 'mime_type="{s.mime_type}"']
if self.includes_video_track:
parts.extend(['res="{s.resolution}"', 'fps="{s.fps}fps"'])
if not self.is_adaptive:
parts.extend(
['vcodec="{s.video_codec}"', 'acodec="{s.audio_codec}"',]
)
else:
parts.extend(['vcodec="{s.video_codec}"'])
else:
parts.extend(['abr="{s.abr}"', 'acodec="{s.audio_codec}"'])
parts.extend(['progressive="{s.is_progressive}"', 'type="{s.type}"'])
return f"<Stream: {' '.join(parts).format(s=self)}>"
|
Printable object representation.
:rtype: str
:returns:
A string representation of a :class:`Stream <Stream>` object.
|
__repr__
|
python
|
pytube/pytube
|
pytube/streams.py
|
https://github.com/pytube/pytube/blob/master/pytube/streams.py
|
Unlicense
|
def __init__(
self,
url: str,
on_progress_callback: Optional[Callable[[Any, bytes, int], None]] = None,
on_complete_callback: Optional[Callable[[Any, Optional[str]], None]] = None,
proxies: Dict[str, str] = None,
use_oauth: bool = False,
allow_oauth_cache: bool = True
):
"""Construct a :class:`YouTube <YouTube>`.
:param str url:
A valid YouTube watch URL.
:param func on_progress_callback:
(Optional) User defined callback function for stream download
progress events.
:param func on_complete_callback:
(Optional) User defined callback function for stream download
complete events.
:param dict proxies:
(Optional) A dict mapping protocol to proxy address which will be used by pytube.
:param bool use_oauth:
(Optional) Prompt the user to authenticate to YouTube.
If allow_oauth_cache is set to True, the user should only be prompted once.
:param bool allow_oauth_cache:
(Optional) Cache OAuth tokens locally on the machine. Defaults to True.
These tokens are only generated if use_oauth is set to True as well.
"""
self._js: Optional[str] = None # js fetched by js_url
self._js_url: Optional[str] = None # the url to the js, parsed from watch html
self._vid_info: Optional[Dict] = None # content fetched from innertube/player
self._watch_html: Optional[str] = None # the html of /watch?v=<video_id>
self._embed_html: Optional[str] = None
self._player_config_args: Optional[Dict] = None # inline js in the html containing
self._age_restricted: Optional[bool] = None
self._fmt_streams: Optional[List[Stream]] = None
self._initial_data = None
self._metadata: Optional[YouTubeMetadata] = None
# video_id part of /watch?v=<video_id>
self.video_id = extract.video_id(url)
self.watch_url = f"https://youtube.com/watch?v={self.video_id}"
self.embed_url = f"https://www.youtube.com/embed/{self.video_id}"
# Shared between all instances of `Stream` (Borg pattern).
self.stream_monostate = Monostate(
on_progress=on_progress_callback, on_complete=on_complete_callback
)
if proxies:
install_proxy(proxies)
self._author = None
self._title = None
self._publish_date = None
self.use_oauth = use_oauth
self.allow_oauth_cache = allow_oauth_cache
|
Construct a :class:`YouTube <YouTube>`.
:param str url:
A valid YouTube watch URL.
:param func on_progress_callback:
(Optional) User defined callback function for stream download
progress events.
:param func on_complete_callback:
(Optional) User defined callback function for stream download
complete events.
:param dict proxies:
(Optional) A dict mapping protocol to proxy address which will be used by pytube.
:param bool use_oauth:
(Optional) Prompt the user to authenticate to YouTube.
If allow_oauth_cache is set to True, the user should only be prompted once.
:param bool allow_oauth_cache:
(Optional) Cache OAuth tokens locally on the machine. Defaults to True.
These tokens are only generated if use_oauth is set to True as well.
|
__init__
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def fmt_streams(self):
"""Returns a list of streams if they have been initialized.
If the streams have not been initialized, finds all relevant
streams and initializes them.
"""
self.check_availability()
if self._fmt_streams:
return self._fmt_streams
self._fmt_streams = []
stream_manifest = extract.apply_descrambler(self.streaming_data)
# If the cached js doesn't work, try fetching a new js file
# https://github.com/pytube/pytube/issues/1054
try:
extract.apply_signature(stream_manifest, self.vid_info, self.js)
except exceptions.ExtractError:
# To force an update to the js file, we clear the cache and retry
self._js = None
self._js_url = None
pytube.__js__ = None
pytube.__js_url__ = None
extract.apply_signature(stream_manifest, self.vid_info, self.js)
# build instances of :class:`Stream <Stream>`
# Initialize stream objects
for stream in stream_manifest:
video = Stream(
stream=stream,
monostate=self.stream_monostate,
)
self._fmt_streams.append(video)
self.stream_monostate.title = self.title
self.stream_monostate.duration = self.length
return self._fmt_streams
|
Returns a list of streams if they have been initialized.
If the streams have not been initialized, finds all relevant
streams and initializes them.
|
fmt_streams
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def check_availability(self):
"""Check whether the video is available.
Raises different exceptions based on why the video is unavailable,
otherwise does nothing.
"""
status, messages = extract.playability_status(self.watch_html)
for reason in messages:
if status == 'UNPLAYABLE':
if reason == (
'Join this channel to get access to members-only content '
'like this video, and other exclusive perks.'
):
raise exceptions.MembersOnly(video_id=self.video_id)
elif reason == 'This live stream recording is not available.':
raise exceptions.RecordingUnavailable(video_id=self.video_id)
else:
raise exceptions.VideoUnavailable(video_id=self.video_id)
elif status == 'LOGIN_REQUIRED':
if reason == (
'This is a private video. '
'Please sign in to verify that you may see it.'
):
raise exceptions.VideoPrivate(video_id=self.video_id)
elif status == 'ERROR':
if reason == 'Video unavailable':
raise exceptions.VideoUnavailable(video_id=self.video_id)
elif status == 'LIVE_STREAM':
raise exceptions.LiveStreamError(video_id=self.video_id)
|
Check whether the video is available.
Raises different exceptions based on why the video is unavailable,
otherwise does nothing.
|
check_availability
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def vid_info(self):
"""Parse the raw vid info and return the parsed result.
:rtype: Dict[Any, Any]
"""
if self._vid_info:
return self._vid_info
innertube = InnerTube(use_oauth=self.use_oauth, allow_cache=self.allow_oauth_cache)
innertube_response = innertube.player(self.video_id)
self._vid_info = innertube_response
return self._vid_info
|
Parse the raw vid info and return the parsed result.
:rtype: Dict[Any, Any]
|
vid_info
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def bypass_age_gate(self):
"""Attempt to update the vid_info by bypassing the age gate."""
innertube = InnerTube(
client='ANDROID_EMBED',
use_oauth=self.use_oauth,
allow_cache=self.allow_oauth_cache
)
innertube_response = innertube.player(self.video_id)
playability_status = innertube_response['playabilityStatus'].get('status', None)
# If we still can't access the video, raise an exception
# (tier 3 age restriction)
if playability_status == 'UNPLAYABLE':
raise exceptions.AgeRestrictedError(self.video_id)
self._vid_info = innertube_response
|
Attempt to update the vid_info by bypassing the age gate.
|
bypass_age_gate
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def caption_tracks(self) -> List[pytube.Caption]:
"""Get a list of :class:`Caption <Caption>`.
:rtype: List[Caption]
"""
raw_tracks = (
self.vid_info.get("captions", {})
.get("playerCaptionsTracklistRenderer", {})
.get("captionTracks", [])
)
return [pytube.Caption(track) for track in raw_tracks]
|
Get a list of :class:`Caption <Caption>`.
:rtype: List[Caption]
|
caption_tracks
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def thumbnail_url(self) -> str:
"""Get the thumbnail url image.
:rtype: str
"""
thumbnail_details = (
self.vid_info.get("videoDetails", {})
.get("thumbnail", {})
.get("thumbnails")
)
if thumbnail_details:
thumbnail_details = thumbnail_details[-1] # last item has max size
return thumbnail_details["url"]
return f"https://img.youtube.com/vi/{self.video_id}/maxresdefault.jpg"
|
Get the thumbnail url image.
:rtype: str
|
thumbnail_url
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def publish_date(self):
"""Get the publish date.
:rtype: datetime
"""
if self._publish_date:
return self._publish_date
self._publish_date = extract.publish_date(self.watch_html)
return self._publish_date
|
Get the publish date.
:rtype: datetime
|
publish_date
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def title(self) -> str:
"""Get the video title.
:rtype: str
"""
if self._title:
return self._title
try:
self._title = self.vid_info['videoDetails']['title']
except KeyError:
# Check_availability will raise the correct exception in most cases
# if it doesn't, ask for a report.
self.check_availability()
raise exceptions.PytubeError(
(
f'Exception while accessing title of {self.watch_url}. '
'Please file a bug report at https://github.com/pytube/pytube'
)
)
return self._title
|
Get the video title.
:rtype: str
|
title
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def author(self) -> str:
"""Get the video author.
:rtype: str
"""
if self._author:
return self._author
self._author = self.vid_info.get("videoDetails", {}).get(
"author", "unknown"
)
return self._author
|
Get the video author.
:rtype: str
|
author
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def metadata(self) -> Optional[YouTubeMetadata]:
"""Get the metadata for the video.
:rtype: YouTubeMetadata
"""
if self._metadata:
return self._metadata
else:
self._metadata = extract.metadata(self.initial_data)
return self._metadata
|
Get the metadata for the video.
:rtype: YouTubeMetadata
|
metadata
|
python
|
pytube/pytube
|
pytube/__main__.py
|
https://github.com/pytube/pytube/blob/master/pytube/__main__.py
|
Unlicense
|
def __init__(self, url: str, proxies: Optional[Dict[str, str]] = None):
"""Construct a :class:`Channel <Channel>`.
:param str url:
A valid YouTube channel URL.
:param proxies:
(Optional) A dictionary of proxies to use for web requests.
"""
super().__init__(url, proxies)
self.channel_uri = extract.channel_name(url)
self.channel_url = (
f"https://www.youtube.com{self.channel_uri}"
)
self.videos_url = self.channel_url + '/videos'
self.playlists_url = self.channel_url + '/playlists'
self.community_url = self.channel_url + '/community'
self.featured_channels_url = self.channel_url + '/channels'
self.about_url = self.channel_url + '/about'
# Possible future additions
self._playlists_html = None
self._community_html = None
self._featured_channels_html = None
self._about_html = None
|
Construct a :class:`Channel <Channel>`.
:param str url:
A valid YouTube channel URL.
:param proxies:
(Optional) A dictionary of proxies to use for web requests.
|
__init__
|
python
|
pytube/pytube
|
pytube/contrib/channel.py
|
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
|
Unlicense
|
def html(self):
"""Get the html for the /videos page.
:rtype: str
"""
if self._html:
return self._html
self._html = request.get(self.videos_url)
return self._html
|
Get the html for the /videos page.
:rtype: str
|
html
|
python
|
pytube/pytube
|
pytube/contrib/channel.py
|
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
|
Unlicense
|
def playlists_html(self):
"""Get the html for the /playlists page.
Currently unused for any functionality.
:rtype: str
"""
if self._playlists_html:
return self._playlists_html
else:
self._playlists_html = request.get(self.playlists_url)
return self._playlists_html
|
Get the html for the /playlists page.
Currently unused for any functionality.
:rtype: str
|
playlists_html
|
python
|
pytube/pytube
|
pytube/contrib/channel.py
|
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
|
Unlicense
|
def community_html(self):
"""Get the html for the /community page.
Currently unused for any functionality.
:rtype: str
"""
if self._community_html:
return self._community_html
else:
self._community_html = request.get(self.community_url)
return self._community_html
|
Get the html for the /community page.
Currently unused for any functionality.
:rtype: str
|
community_html
|
python
|
pytube/pytube
|
pytube/contrib/channel.py
|
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
|
Unlicense
|
def featured_channels_html(self):
"""Get the html for the /channels page.
Currently unused for any functionality.
:rtype: str
"""
if self._featured_channels_html:
return self._featured_channels_html
else:
self._featured_channels_html = request.get(self.featured_channels_url)
return self._featured_channels_html
|
Get the html for the /channels page.
Currently unused for any functionality.
:rtype: str
|
featured_channels_html
|
python
|
pytube/pytube
|
pytube/contrib/channel.py
|
https://github.com/pytube/pytube/blob/master/pytube/contrib/channel.py
|
Unlicense
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.