Search code examples
pythonwindowspython-requestsurllibmp4

Can't open downloaded .mp4 files downloaded with requests and urllib


I've downloaded some files using requests

url = 'https://www.youtube.com/watch?v=gp5tziO5lXg&feature=youtu.be'
video_name = url.split('/')[-1]

print("Downloading file:%s" % video_name)

# download the url contents in binary format
r = requests.get(url)

# open method to open a file on your system and write the contents
with open('saved.mp4', 'wb') as f:
    f.write(r.content)

and using urllib.requests

url = 'https://www.youtube.com/watch?v=gp5tziO5lXg&feature=youtu.be'
video_name = url.split('/')[-1]

print("Downloading file:%s" % video_name)

# Copy a network object to a local file
urllib.request.urlretrieve(url, "saved2.mp4")

When I then try to open the .mp4 file I get the following error

Cannot play

This file cannot be played. This can happen because the file type is not supported, the file extension is incorrect or the file is corrupted.

0xc00d36c4

Cannot open .mp4 file

If I test it with pytube it works fine.

What's wrong with the other methods?


Solution

  • To answer your question, with the other methods it is not downloading the video but the page. What you may be obtaining is an html file with an mp4 file extension.

    Therefore, it gives that error when trying to open the file.

    If pytube works for what you need, I would suggest using that one.

    If you want to download videos from other platforms, you might consider youtube-dl.