'How to download a video directly from a url using python?

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)     


Solution 1:[1]

That is because you must have an url finishing in .mp4. If you don't have that, requests will process and download the page that you see when entering to the YouTube url.

You con try other modules like youtube-dl (youtube-dl from pypi) or you can try (I don't know if that is possible) to scrape the data of the YouTube url page for extracting the url of the video.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toni Ivars JuliĆ