本文整理汇总了Python中pytube.YouTube方法的典型用法代码示例。如果您正苦于以下问题:Python pytube.YouTube方法的具体用法?Python pytube.YouTube怎么用?Python pytube.YouTube使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytube
的用法示例。
在下文中一共展示了pytube.YouTube方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_youtube
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def download_youtube(url, output):
"""Download YouTube videos.
Args:
url (str): YouTube video url.
output (str): Download directory.
Returns:
bool: Return True if the video was downloaded and False if get an exception.
"""
try:
YouTube(url).streams.first().download(output)
return True
except Exception:
return False
示例2: generate_search_url
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def generate_search_url(self, query):
"""
Generates a search URL for YouTube for a given search query.
Parameters
----------
query: `str`
The search query.
Returns
-------
search_url: `str`
A URL which corresponds to YouTube search results.
"""
quoted_query = urllib.request.quote(query)
search_url = self.base_search_url.format(quoted_query)
return search_url
示例3: _fetch_search_results
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def _fetch_search_results(self, html, limit=10):
videos_html = html.find_all(
"div", {"class": "yt-lockup-dismissable yt-uix-tile"}
)
if videos_html:
return self._fetch_search_results_from_html(videos_html, limit=limit)
# Sometimes YouTube can go crazy and return JSON data instead
# of an HTML response. Handle such cases.
logger.debug("YouTube returned malformed HTML. Attempting to parse possible JSON data.")
html = str(html)
search_start = 'window["ytInitialData"] = '
videos_json_start = html.find(search_start) + len(search_start)
search_end = "}}]}}}}}}"
videos_json_end = videos_json_start + html[videos_json_start:].find(search_end) + len(search_end)
videos_json = html[videos_json_start:videos_json_end] + "}"
try:
videos_json = json.loads(videos_json)
except json.decoder.JSONDecodeError:
return []
return self._fetch_search_results_from_json(videos_json, limit=limit)
示例4: from_url
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def from_url(self, url, retries=5):
logger.debug('Fetching YouTube metadata for "{url}".'.format(url=url))
try:
content = pytube.YouTube(url)
except KeyError:
# Sometimes YouTube can return unexpected response, in such a case
# retry a few times before finally failing.
if retries > 0:
retries -= 1
logger.debug(
"YouTube returned an unexpected response for "
"`pytube.YouTube({url})`. Retries left: {retries}".format(
url=url, retries=retries
)
)
return self.from_url(url, retries=retries)
else:
raise
else:
return self.from_pytube_object(content)
示例5: download_video
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def download_video(url, start=0, stop=0):
def on_downloaded(stream, file_handle):
# get filename of downloaded file (we can't set a output directory) and close the handle
fn = file_handle.name
file_handle.close()
# load downloaded video
clip = VideoFileClip(fn)
# clip with start and stop
if(start >= 0 and stop >= 0):
clip = clip.subclip(start, stop)
# store clipped video in our temporary folder
clip.write_videofile("./temp/src_video.mp4", progress_bar=False, verbose=False)
# remove original downloaded file
os.remove(fn)
# download youtube video from url
yt = YouTube(url)
# clip file after downlaod
yt.register_on_complete_callback(on_downloaded)
# get first "mp4" stream as explained here: https://github.com/nficano/pytube
yt.streams.filter(subtype='mp4').first().download()
示例6: download_video
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def download_video(url, start=0, stop=0):
def on_downloaded(stream, file_handle):
# get filename of downloaded file (we can't set a output directory) and close the handle
fn = file_handle.name
file_handle.close()
# load downloaded video into moviepy
clip = VideoFileClip(fn)
# clip with start and stop
if(start >= 0 and stop >= 0):
clip = clip.subclip(start, stop)
# store clipped video in our temporary folder
clip.write_videofile("./temp/src_video.mp4", progress_bar=False, verbose=False)
# remove original downloaded file
os.remove(fn)
# download youtube video from url
yt = YouTube(url)
yt.register_on_complete_callback(on_downloaded)
yt.streams.filter(subtype='mp4').first().download()
示例7: youtube_streams
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def youtube_streams(self, context):
"""
This methods returns a list of YouTube stream attributes. Fields
returned include itag, mime_type and res.
Example:
[['22', 'video/mp4', '720p']]
:param pytube.YouTube context: An instance of the pytube.YouTube class.
:rtype: list(list(str, str, str))
"""
streams = []
for stream in context.streams.all():
streams.append([stream.itag, stream.mime_type, stream.resolution])
return streams
示例8: youtube_select
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def youtube_select(self, streams):
"""
This method selects a YouTube stream to download.
:param list(list(str, str, str)) streams: A list of YouTube stream
attributes.
:rtype: list(str, str, str)
"""
selected = None
for stream in streams:
if stream[1] == 'video/mp4':
if selected is None:
selected = stream
else:
if stream[2]:
# It is assumed that resolution is formatted as '\d+p'.
if int(stream[2][0:-1]) > int(selected[2][0:-1]):
selected = stream
return selected
示例9: list_streams
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def list_streams(url, audio_only=False, proxies=None):
if 'https' not in url:
url = 'https://www.youtube.com/watch?v=%s' % url
if proxies:
video = YouTube(url, proxies=proxies)
else:
video = YouTube(url)
print(f'{video.title}')
for stream in video.streams.filter(only_audio=audio_only).all():
if audio_only:
print(f'ITAG: {stream.itag}, Codec: {stream.audio_codec}, '
f'ABR: {stream.abr}, File Type: {stream.mime_type.split("/")[1]}')
else:
if stream.video_codec is None:
continue
print(f'ITAG: {stream.itag}, Res: {stream.resolution}, FPS: {stream.fps}, '
f'Video Codec: {stream.video_codec}, Audio Codec: {stream.audio_codec}, '
f'File Type: {stream.mime_type.split("/")[1]}')
print('\n\nTo download a specific stream, use the -i/--itag argument and provide the ITAG ID.')
示例10: parse_args
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def parse_args():
parser = argparse.ArgumentParser(description='YouTube Video/Audio Downloader')
parser.add_argument('-u', '--url', help='YouTube URL or YouTube Video ID to download', default=None)
parser.add_argument('-l', '--list-streams', help='List available streams for this YouTube Video '
'instead of download. Use -a/--audio-only to list audio streams. '
'Download specific stream with the '
'itag ID and -i/--itag argument.',
action='store_true', default=False)
parser.add_argument('-i', '--itag', help='Stream ITAG to download for given YouTube Video/ID. '
'List streams with -l/--list-streams argument. '
'If ITAG is not provided, default stream will be downloaded. '
'Downloading with ITAG ignores -a/--audio-only.', type=int, default=None)
parser.add_argument('-o', '--output-path', help='Output Directory Path', default=None)
parser.add_argument('-f', '--filename', help='Override the output filename. Does not override file extension',
default=None)
parser.add_argument('-p', '--proxy', help='Proxy to use. Ex http://xxx.xxx.xxx:8080 '
'NOTE: You need https proxy for https URL!', default=None)
parser.add_argument('-a', '--audio-only', help='Download Audio Only', action='store_true', default=False)
parsed_args = parser.parse_args()
if parsed_args.proxy:
parsed_args.proxy = {parsed_args.proxy.split(':')[0]: parsed_args.proxy}
return parsed_args
示例11: threaded_check_video
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def threaded_check_video(self):
self.last_row = 0
self.stream.set(0)
[radio_button.destroy() for radio_button in self.stream_widgets]
url = self.text_url.get()
if 'https' not in url:
url = 'https://www.youtube.com/watch?v=%s' % url
try:
if self.proxy.get() != '':
self.video = YouTube(url, proxies={self.proxy.get().split(':')[0]: self.proxy.get()})
else:
self.video = YouTube(url)
self.label_video_title['text'] = self.video.title
self.streams = self.video.streams.filter(only_audio=self.audio_only.get()).all()
for stream in self.streams:
if self.audio_only.get():
text = f'Codec: {stream.audio_codec}, ' \
f'ABR: {stream.abr} ' \
f'File Type: {stream.mime_type.split("/")[1]}, Size: {stream.filesize // 1024} KB'
else:
if stream.video_codec is None:
continue
text = f'Res: {stream.resolution}, FPS: {stream.fps},' \
f' Video Codec: {stream.video_codec}, Audio Codec: {stream.audio_codec}, ' \
f'File Type: {stream.mime_type.split("/")[1]}, Size: {stream.filesize // 1024} KB'
radio_button = tk.Radiobutton(self.frame, text=text, variable=self.stream, value=stream.itag)
self.last_row += 1
radio_button.grid(row=self.last_row, column=0, columnspan=4)
self.stream_widgets.append(radio_button)
except PytubeError as e:
messagebox.showerror('Something went wrong...', e)
except RegexMatchError as e:
messagebox.showerror('Something went wrong...', e)
finally:
self.btn_check_id['text'] = 'Check Video'
self.btn_check_id.config(state=tk.NORMAL)
示例12: search_all_files
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def search_all_files(search_url, youtube_object=YouTube()):
search_url = search_url
urls = get_urls(search_url)
yt = youtube_object
for url in urls:
try:
print "downloading " + url
yt.url = url
video = yt.get('mp4', '720p')
filename = yt.filename
video.download()
time.sleep(.1)
cc = getyoutubecc.getyoutubecc(yt.video_id,'en')
cc.writeSrtFile(filename + '.srt')
time.sleep(.1)
except:
print "couldn't download " + url
示例13: getVideoFromYoutube
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def getVideoFromYoutube(self,text):
'''
Getting song url from YouTube
:param text: name of song
:return: list of results
'''
#logging.info(f"Finding")
request = self.__url + str(text).replace(' ','+')
response = requests.get(request, headers=self.headers)
soup = BeautifulSoup(response.text,'lxml')
self.__result = []
for link in soup.findAll(attrs={'class': 'yt-uix-tile-link'}):
self.__result.append(self.__host + link['href'])
self.removeInvallidLinks()
return self.__result
示例14: getNameFromYoutube
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def getNameFromYoutube(self, url):
response = requests.get(url, headers=self.headers)
soup = BeautifulSoup(response.text,'lxml')
_title = soup.find('title').text
_title = str(_title).replace(' - YouTube', '')
_result = []
__name = None
if not str(_title).find('-') > -1:
for link in soup.findAll('meta', attrs={'property': 'og:video:tag'}):
_result.append(link.get('content'))
if len(_result) > 1:
name = f"{_result[0]} - {_title}"
else:
name = _title
else:
name = _title
return name
示例15: search
# 需要导入模块: import pytube [as 别名]
# 或者: from pytube import YouTube [as 别名]
def search(self, query, limit=10, retries=2):
"""
Search and scrape YouTube to return a list of matching videos.
Parameters
----------
query: `str`
The search query.
limit: `int`
Return only first n results.
retries: `int`
YouTube can sometimes return invalid response. Maximum
number of retries to make in such case.
Returns
-------
videos: An instance of :class:`spotdl.metadata.providers.youtube.YouTubeVideos`.
"""
search_url = self.generate_search_url(query)
logger.debug('Fetching YouTube results for "{}" at "{}".'.format(query, search_url))
html = self._fetch_response_html(search_url)
videos = self._fetch_search_results(html, limit=limit)
to_retry = retries > 0 and self._is_server_side_invalid_response(videos, html)
if to_retry:
logger.debug(
"Retrying since YouTube returned invalid response for search "
"results. Retries left: {retries}.".format(retries=retries)
)
return self.search(query, limit=limit, retries=retries-1)
videos = YouTubeVideos(videos)
return videos