[Python] How to download a video directly from a url using python?

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to python and I want to download a video from a given URL. So far I've heard about urllib, urllib2 and requests modules that help to download a video from URL, but when I tried them I apparently got all the data on that page and I don't know what I got, or even if the video is in there since the size of the output file is usually 50-170 KB and videos are usually way more than that. I'll post two codes of mine that are meant to download a video so you can tell me if they have any problem. If they are okay, can you tell me how to separate the video from what I got or if the video is even there?

    1.

    import requests

    def download_file(url):
    local_filename = url.split('/')[-1]

    r = requests.get(url, stream=True)
    with open("D://"+local_filename, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024):
    if chunk:
    f.write(chunk)

    earl = "https://www.youtube.com/watch?v=DBYjZTdrJlA"
    download_file(earl)


    2.

    import urllib2
    import os


    earl="https://www.youtube.com/watch?v=DBYjZTdrJlA"
    y= True
    try: response=urllib2.urlopen(earl)
    except urllib2.HTTPError:
    print "oopsy, website wont allow it"
    y=False


    def downloader(url):
    response=urllib2.urlopen(url)
    info = response.read()
    print info
    fx= open(os.path.join("D://", "video.mp4"),'wb')
    for line in info:
    fx.write(line)
    fx.close()
    print "done"

    if(y):
    downloader(earl)

    Continue reading...

Compartilhe esta Página