Search code examples
pythonpython-3.xcsvvideopytube

Using pytube library to download youtube links from csv


I'm trying to use the pytube library to download a bunch of links I have on a .csv file.

EDIT:

WORKING CODE:

   import sys
reload(sys)
sys.setdefaultencoding('Cp1252')

import os.path

from pytube import YouTube
from pprint import pprint

import csv
with open('onedialectic.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            try:
                yt = YouTube(row[1])
                path = os.path.join('/videos/',row[0])
                path2 = os.path.join(path + '.mp4')
                print(path2)
                if not os.path.exists(path2) :
                                print(row[0] + '\n')
                                pprint(yt.get_videos())
                                yt.set_filename(row[0])
                                video = yt.get('mp4', '360p')
                                video.download('/videos')
            except Exception as e:
                print("Passing on exception %s", e)
                continue

Solution

  • To install it you need to use

    pip install pytube
    

    and then in your code run

    from pytube import YouTube
    

    I haven't seen any code examples of using this with csv though, are you sure it's supported?

    You can download via command line directly using e.g.

    $ pytube -e mp4 -r 720p -f Dancing Scene from Pulp Fiction http://www.youtube.com/watch?v=Ik-RsDGPI5Y
    

    -e, -f and -r are optional, (extension, filename and resolution)

    However for you I would suggest maybe the best thing is to put them all in a playlist and then use Jordan Mear's excellent Python Youtube Playlist Downloader

    On a footnote, usually all [external] libraries need to be imported. You can read more about importing here, in the python online tutorials

    You could maybe do something like this:

    import csv
    from pytube import YouTube
    
    vidcsvreader = csv.reader(open("videos.csv"), delimiter=",")
    
    header1 = vidcsvreader.next() #header
    
    
    for id, url in vidcsvreader:
        yt = url  #assign url to var
    
        #set resolution and filetype
        video = yt.get('mp4', '720p')
    
        # set a destination directory for download
        video.download('/tmp/')
    
        break