55

I have tried the following code to download a video in YouTube and it is working, but I want to save the video at a particular location. Now it is saving the video in C:/Users/Download. If I want to save the video in the desktop, what changes do I need in the code?

from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])
2

13 Answers 13

97

I found out a really cool python module that allows you to download videos from youtube easily. TO install it:

pip install pytube

Now, You can download your video like this -

from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=n06H7OcPd-g")
yt = yt.get('mp4', '720p')
yt.download('/path/to/download/directory')

Boom, Now you can easily scrape such videos using Python easily; Now, We Drink!

Update 1:

Thanks to @Chiramisu's comment, You can use the following one-liner to download the highest quality video:

YouTube('video_url').streams.first().download('save_path')

For Windows, please specify path with double backslashes ex:

YouTube('video_url').streams.first().download('C:\\Users\\username\\save_path')

Update 2:

If pytube doesn't seem to work for you, try using youtube-dl:

pip install --upgrade youtube-dl

Now Download Videos:

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

More info on ytdl in python here.

14
  • i don't understand where the video variable/object came from? Commented Oct 25, 2017 at 1:29
  • 12
    AttributeError: 'YouTube' object has no attribute 'get'
    – Vallie
    Commented Apr 4, 2018 at 5:36
  • 8
    One-liner updated logic: YouTube('video_url').streams.first().download('save_path'). This will download highest quality video, but 1080p or above will be separate files for video and audio which will need to be joined with FFmpeg or some such utility.
    – Chiramisu
    Commented Aug 14, 2018 at 5:04
  • 2
    @mLstudent33 check the udpate 2 in my answer
    – Daksh M.
    Commented Aug 18, 2019 at 4:58
  • 1
    YouTube('video_url').streams.first() didn't get me the highest res. I solved it with yt.streams.filter(res="1080p").first().download()
    – John Funk
    Commented Aug 15, 2020 at 23:35
27

downloading videos from youtube in python 3.x for the reference you can check https://python-pytube.readthedocs.io/en/latest/user/quickstart.html#downloading-a-video

from pytube import YouTube
import os

def downloadYouTube(videourl, path):

    yt = YouTube(videourl)
    yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
    if not os.path.exists(path):
        os.makedirs(path)
    yt.download(path)

downloadYouTube('https://www.youtube.com/watch?v=zNyYDHCg06c', './videos/FindingNemo1')
1
  • I think your code is probably fine but I'm getting a KeyError: s, seems like an open issue on github. Commented Jul 14, 2019 at 8:08
13

You should put it inside ydl_opts:

ydl_opts = {
    'outtmpl': os.path.join(download_path, '%(title)s-%(id)s.%(ext)s'),
}

In your case, download_path should be 'C:/Users/Desktop'. Use %(title)s.%(ext)s instead of %(title)s-%(id)s.%(ext)s if you prefer a file name without video ID.

Or you can just os.chdir(path) to change the directory to where you want the download to be before you start your download.

from __future__ import unicode_literals
import youtube_dl
import os

ydl_opts = {}
os.chdir('C:/Users/Desktop')
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])
3
  • if I want to save the file on google cloud storage, can i still define the path using os.chdir, such that the downloaded video could be saved in gcs. Commented Aug 21, 2019 at 2:30
  • Do you have access to gcs in File Explorer/Finder? If so, probably yes. I can save files directly in my google drive, which is mounted as a volume on my mac.
    – thyu
    Commented Sep 1, 2019 at 21:07
  • 1
    Exactly what I wanted. Rest of the answers are too focused on other packages while the OP clearly mentioned youtube-dl.
    – abdev
    Commented Apr 19, 2020 at 18:25
4
Path = "The Path That You Want"
Location = '%s \%(extractor)s-%(id)s-%(title)s.%(ext)s'.replace("%s ", Path)
ytdl_format_options = {
'outtmpl': Location
}

with youtube_dl.YoutubeDL(ytdl_format_options) as ydl:
     ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])

I personally don't know the library very well, but here is my knowledge the youtube_dl have ytdl_format_options it gives you the options to add some I don't know what it called but let say parameters like above outtmp1 give you the option to specify the location, id, title, or quiet to see the log or not and there is so much more. almost everything you can get it from this URL:https://github.com/ytdl-org/youtube-dl/blob/master/README.md#format-selection

2
  • 3
    Please include an explanation about this code you have posted. Commented Jun 25, 2019 at 15:04
  • This is the correct answer, it should have more upvotes. I wonder if there is a way to obtain the name of the downloaded file for further processing.
    – Vincenzooo
    Commented Aug 31, 2022 at 22:14
4

-> Uninstall pytube (if is present)

pip uninstall pytube

-> Install:

pip install pytube3

-> Modify extract.py in environment:

lib/pytube/extract.py

-> Find and edit line:

parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)

-> change it to:

parse_qs(formats[i]["signatureCipher"]) for i, data in enumerate(formats)

-> Use pytube:

from pytube import YouTube
import os


def downloadYoutube(vid_url, path):
    yt = YouTube(vid_url)
    yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
    if not os.path.exists(path):
        os.makedirs(path)

    yt.download(path)

url = input('Input url:\n')
path = input('Path to store file:\n')
downloadYoutube(url, path)
2

youtube_dl has a giant list of options: https://github.com/rg3/youtube-dl/blob/master/youtube_dl/YoutubeDL.py#L128-L278

But I don't see any that control the output directory. So you can move the file afterward. For that, see: How to move a file in Python.

1
  • I have tried the following code source = 'C:\Users\Sharmili Nag\Aahatein - Agnee (splitsvilla 4 theme song) Best audio quality-n06H7OcPd-g.mp4' destination = 'C:\Users\Sharmili Nag\Desktop' import os os.rename(source,destination) but i am getting this error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in positio n 2-3: truncated \UXXXXXXXX escape Commented Nov 21, 2016 at 6:04
2

It will save the file where your .py application is in. for example, if your .py program is in your desktop folder and you run your app from the desktop, the output will save on your desktop. the only thing you need is to save your .py file in Desktop and then open a command line and go in Desktop using cd command after it run your .py file using python YOURAPP.py but if you want to download it and then save it in another place, you need to download it like you do now (in your temporary place) then moves it via file libraries in python.

2

It looks like pytube has changed a little bit since the top answer for the question was originally posted. Here is an updated example for working with PyTube v11.0.2 (January 9th, 2022):

'''
HOW TO: Download YouTube Videos Programmatically with Python & pytube

$ pip install pytube

$ python3 download.py
'''

from pytube import YouTube

def on_progress(stream, chunk, bytes_remaining):
    print("Downloading...")

def on_complete(stream, file_path):
    print("Download Complete")

yt = YouTube(
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
        on_progress_callback=on_progress,
        on_complete_callback=on_complete,
        use_oauth=False,
        allow_oauth_cache=True
    )

yt.streams.filter(file_extension='mp4', res="720p").first().download()
2
  • How to save the video to the user downloads directory , if the user has a mobile phone , how to save the video into the phone ?
    – Ekane 3
    Commented Jan 19, 2022 at 14:56
  • pytube is broken above code produces KeyError: 'streamingData' Commented Apr 28, 2023 at 11:49
2

I did some changes in the answer of @orlov_dumitru and it worked fine.

#!/usr/bin/env python
import os
import sys
from pytube import YouTube



def downloadYoutube(vid_url, path):
    yt = YouTube(vid_url)
    yt = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
    if not os.path.exists(path):
        os.makedirs(path)

    yt.download(path)


# video url
url = sys.argv[1]
# path to where you want to save the video
path = sys.argv[2]
downloadYoutube(url, path)
exit()
1
from __future__ import unicode_literals
import youtube_dl

ydl_opts = {
    'outtmpl': 'yourPathToDirectory/%(title)s.%(ext)s',

}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=XpYGgtrMTYs'])

ydl_opts is the what we need to play with. We can declare multiple attributes/parameters inside this for customisation. For this example, I've added a single attribute outtmpl which is used to define custom directory. We can further customize this to declare filename, etc.

0
pip3 install pytube

    
yt_url = "https://youtu.be/k8oMuLWiUzo"
from pytube import YouTube
yt = YouTube(yt_url)
yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
0

pip install youtube-dl didn't work for me,

but this worked for me:

pip install git+https://github.com/ytdl-org/youtube-dl.git@master#egg=youtube_dl

-5

I guess you are a bit confused, try this code, end to end

    from __future__ import unicode_literals
    import youtube_dl
    import urllib
    import shutil
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])

    #Moving your source file to destination folder
    source_file = 'C:\Users\Sharmili Nag\Aahatein - Agnee (splitsvilla 4 theme song) Best audio quality-n06H7OcPd-g.mp4'
    destination_folder = 'C:\Users\Sharmili Nag\Desktop\Aahatein - Agnee (splitsvilla 4 theme song) Best audio quality-n06H7OcPd-g.mp4'
    shutil.move(source_file, destination_folder)

In case this code worked out for you, kindly mark the answer as correct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.