Search code examples
pythonpytube

pytube urllib.error.HTTPError: HTTP Error 404: Not Found


I tried to create a script to download a Youtube video. Sometime it works but sometime it comes out with a 'HTTP Error 404' error. Below is the code:

/*** A001MainMenu.py ***/

from C001Youtube import C001_YouTube

vlink = input("Enter the link: ")
fer = "D:\ABC\Youtube"

video = C001_YouTube(vlink, fer, None)
C001_YouTube.DVideo(video, vlink, fer, None)

/*** C001YouTube.py ***/

from pytube import YouTube
from pytube import extract
import ffmpeg

class C001_YouTube:

    def __init__(self, video_link, folder, maxres):
        self.video_link = video_link
        self.folder = folder
        self.maxres = maxres

    def checkfilename(self, filename):
        deletechars = "\"" + '"' + "\\" + "/:*?<>|"
        print(deletechars)
        for c in deletechars:
            filename = filename.replace(c, '')
        return filename

    def setfilename(self, video_link):
        filename = extract.video_id(video_link) + "_" + YouTube(video_link).title
        fname = self.checkfilename(filename)
        return fname

    def DVideo(self, video_link, folder, maxres=None):
        video_name = self.setfilename(video_link)
        print(video_name)
        if maxres is None:
            print("Video Started 2")
            video_file = YouTube(self.video_link).streams.order_by('resolution').desc().first().download()
            print(" Video Done 1")

        else:
            print("Video Started 3")
            video_file = YouTube(self.video_link).streams.filter(res=maxres).order_by('resolution').desc().first().download()
            print("Video Done 2")

        print("Audio Started")
        audio_file = YouTube(self.video_link).streams.filter(only_audio=True).order_by('abr').desc().first().download(filename_prefix="audio_")
        print("Audio Done")

        source_audio = ffmpeg.input(audio_file)
        source_video = ffmpeg.input(video_file)

        print("Concatenation Started")
        ffmpeg.concat(source_video, source_audio, v=1, a=1).output(f"{folder}\{video_name}.mp4").run()
        print("Concatenation Done")

        return None

Below is a sample video link that works: https://www.youtube.com/watch?v=bH7dRlbEDJY Below is a sample video link that is not worked (Error 404): https://www.youtube.com/watch?v=DjbhQJhXfs8

It would be grateful if someone can give me a hand to understand why sometime the code is working and sometime isn't. Thanks a lot in advance.


Solution

  • This is a known bug with pytube.

    I ran into this problem the first time last month but then it seems to have been resolved until now I'm start seeing it again. You'll just have to wait for the next pytube update, hopefully in which the issue will be resolved.

    You can try upgrading pytube by running this command pip install pytube --upgrade whenever the new update is out which will potentially solve the issue.