Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python download youtube with specific filename

I'm trying to download youtube videos with pytube this way:

from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()

but the file will have the same name as the original video name. How do I specify a custom filename?

like image 503
ehsan shirzadi Avatar asked Dec 05 '17 08:12

ehsan shirzadi


People also ask

How do I download YouTube videos with Python?

pytube library makes the video downloading very easy. Create the object of the YouTube module by passing the link as the parameter. Then, get the appropriate extension and resolution of the video. You can set the name of the file as your convenience, in another case original name will be kept.

Is Pytube safe to use?

Is pytube safe to use? The python package pytube was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.

How do I download playlists from Pytube?

from pytube import Playlist playlist = Playlist('https://www.youtube.com/playlist?list=PLeo1K3hjS3uvCeTYTeyfe0-rN5r8zn9rw') print('Number of videos in playlist: %s' % len(playlist. video_urls)) # Loop through all videos in the playlist and download them for video in playlist. videos: try: print(video. streams.


2 Answers

UPDATE:

The feature is now added. You can now use the below mentioned feature without downloading the repository.

Old answer:

This is not possible in the current latest (v7.0.18) release. The feature has been added, but no new release has been released since then. If you want to have this feature, you need to download the pytube repository: https://github.com/NFicano/pytube

If you have done so, you can use YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download(filename='filename')

It will automatically add the filename extension, so you don't have to include that.

I found it by reading the source. There, I found the declaration of the function download in the file streams.py:

def download(self, output_path=None, filename=None):

So you can obviously also specify a path.

For a good workaround, see landogardner's answer.

like image 109
klutt Avatar answered Sep 22 '22 10:09

klutt


To add to klutt's answer, it doesn't look like there's been a new pypi release since this feature was added, so for now you can either download the code directly as klutt suggests, or, as a workaround, manually rename the file after the download() call, e.g.:

import os
from pytube import YouTube

yt = YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
yt.streams.first().download()
os.rename(yt.streams.first().default_filename, 'new_filename.ext')`
like image 35
scrpy Avatar answered Sep 23 '22 10:09

scrpy