51

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'])
johan
  • 1,664
  • 2
  • 14
  • 30
Sharmili Nag
  • 663
  • 2
  • 8
  • 10
  • 1
    Actually, the answer to that question is to add `-o` option to the command line in order to set your output file, refer to [GitHub example](https://github.com/ytdl-org/youtube-dl#output-template-examples). – Joe Nov 01 '19 at 16:15
  • 1
    simply set 'outtmpl' in `ydl_opts`: https://stackoverflow.com/questions/35643757/how-to-set-directory-in-ydl-opts-in-using-youtube-dl-in-python – johan Apr 19 '20 at 19:11

12 Answers12

91

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.

zabop
  • 6,750
  • 3
  • 39
  • 84
Daksh M.
  • 4,589
  • 4
  • 30
  • 46
  • i don't understand where the video variable/object came from? – jameshwart lopez Oct 25 '17 at 01:29
  • pytube is very slow, how other online platforms are able to download it so fast ?? I have a very fast 16 Mbps connection, but its downloading at the speed of 512 kbps or so – nowonder Nov 24 '17 at 09:55
  • 10
    `AttributeError: 'YouTube' object has no attribute 'get' ` – Vallie Apr 04 '18 at 05:36
  • @Vallie vist there repository on GitHub – Maged Saeed May 14 '18 at 22:24
  • 8
    One-liner [updated logic](https://github.com/nficano/pytube#getting-started): `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 Aug 14 '18 at 05:04
  • I'm getting the same error too here. `AttributeError: 'YouTube' object has no attribute 'get' ` –  Mar 07 '19 at 18:36
  • @DakshMiglani I'm getting an error: `KeyError: 's'` – mLstudent33 Jun 22 '19 at 05:37
  • I'll check in a bit – Daksh M. Jun 22 '19 at 05:46
  • @DakshMiglani pytube seems really broken. `Key error title` among others listed on Github and fixes provided to edit source code files but the recommended install method is `pip install pytube` so that does not give us source code right? What do you suggest? – mLstudent33 Aug 18 '19 at 04:46
  • 2
    @mLstudent33 check the udpate 2 in my answer – Daksh M. Aug 18 '19 at 04: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 Aug 15 '20 at 23:35
  • @JohnFunk well the best solution is to use ytdl imo. – Daksh M. Aug 16 '20 at 10:40
  • When installing pytube at 9.6.0, YouTube module cannot be imported with the error message 'ImportError: cannot import name urlencode' – Jiaxiang Sep 01 '21 at 07:17
  • First best quality: `YouTube('video_url').streams.filter(progressive=True).order_by('resolution').desc().first().download('target_dir')` – Artem S. Zhelonkin Apr 23 '23 at 10:00
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')
Azadeh Khojandi
  • 3,806
  • 1
  • 30
  • 32
12

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'])
johan
  • 1,664
  • 2
  • 14
  • 30
  • 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. – Analytics_TM Aug 21 '19 at 02: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. – johan Sep 01 '19 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 Apr 19 '20 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

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.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 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 – Sharmili Nag Nov 21 '16 at 06: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.

SdSaati
  • 798
  • 9
  • 18
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()
topherPedersen
  • 541
  • 7
  • 15
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()
0
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.

Apurv
  • 391
  • 2
  • 9
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()
Onkar Chougule
  • 161
  • 1
  • 3
-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.

Aakash Makwana
  • 734
  • 5
  • 9