urllib.error.HTTPError:HTTP 错误 400:错误请求 - Pytube

问题描述 投票:0回答:1

我的 pytube 下载程序最近突然停止工作并返回此错误:

Traceback (most recent call last):
  File "C:\Users\winte\Music\{Python#playlister}.py", line 191, in <module>
    DownloadPlaylist(LinkInput)
  File "C:\Users\winte\Music\{Python#playlister}.py", line 101, in DownloadPlaylist
    Streams = Video.streams.filter(file_extension='mp4').last()
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 296, in streams
    return StreamQuery(self.fmt_streams)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 176, in fmt_streams
    stream_manifest = extract.apply_descrambler(self.streaming_data)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 157, in streaming_data
    if 'streamingData' in self.vid_info:
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\__main__.py", line 246, in vid_info
    innertube_response = innertube.player(self.video_id)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\innertube.py", line 300, in player
    return self._call_api(endpoint, query, self.base_data)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\innertube.py", line 242, in _call_api
    response = request._execute_request(
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\request.py", line 37, in _execute_request
    return urlopen(request, timeout=timeout)  # nosec
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
    response = self.parent.error(
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\winte\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

供参考,这是我的代码:

from pytube import YouTube, Playlist, exceptions
import os
from moviepy.editor import *
import time

#Set output directory to playlist downloader
root_dir = (os.path.dirname(__file__))
os.chdir(f"{root_dir}/Playlist downloader")

#Get download desired properties from user
DownloadType = input("Type v or p to download a video or playlist --> ")
DesiredFileFormat = input("Type mp3 or mp4 to download as mp3 or mp4 --> ")


def DownloadVideo(VideoLink):

    #Defines video object
    try:
        Video = YouTube(VideoLink, use_oauth=True, allow_oauth_cache=True)
        
    #Prevents total program error if video is not available
    except exceptions.VideoUnavailable:
        print(f'Video {VideoLink} is unavaialable')
            

    
            
    #Downloads mp4 from video object
    else:
        try:
            Title = Video.title
        except:
            Title = "N/A"
        #Notifies user that video download has begun
        print(f'Downloading video: {Title}')

        #Find stream
        Stream = Video.streams.filter(file_extension='mp4').last()
        
        #Downloads mp4 from stream
        Stream.download(output_path=f"{root_dir}/Playlist downloader")
        print("download is complete...")

def DownloadAudio(VideoLink):

    #Defines video object
    try:
        Video = YouTube(VideoLink, use_oauth=True, allow_oauth_cache=True)
        
    #Prevents total program error if video is not available
    except exceptions.VideoUnavailable:
        print(f'Video {VideoLink} is unavaialable')
            

    
            
    #Downloads mp4 from video object
    else:
        try:
            Title = Video.title
        except:
            Title = "N/A"
        #Notifies user that video download has begun
        print(f'Downloading video: {Title}')

        #Find stream
        Stream = Video.streams.filter(file_extension='mp4', only_audio=True).last()
        
        #Downloads mp4 from stream
        Stream.download(output_path=f"{root_dir}/Playlist downloader")
        print("download is complete...")

def DownloadPlaylist(PlaylistLink):

    CurrentVideoNumber = 0 #The index of the current video in the playlist
    VideoList = Playlist(PlaylistLink) #Defines playlist object

    #Gets link of each video
    for VideoLink in VideoList.video_urls:

        #Make video object for current url
        try:
            Video = YouTube(VideoLink, use_oauth=True, allow_oauth_cache=True)

        #Prevents total program error if video is not available
        except exceptions.VideoUnavailable:
            print(f'Video {VideoLink} is unavaialable, skipping.')
            continue
        
        #Download current video
        else:
            try:
                Title = Video.title
            except:
                Title = "N/A"

            CurrentVideoNumber += 1 #Changes old video index to the current one
            print(f'Downloading video: {Title}') #Tells user that current video has begun download

            #Get stream
            Streams = Video.streams.filter(file_extension='mp4').last()

            #Download video from stream
            Streams.download(output_path=f"{root_dir}/Playlist downloader")
            print(f"{CurrentVideoNumber} of {len(VideoList.video_urls)} is complete...") #Tells user that current video download is complete

def DownloadPlaylistAudio(PlaylistLink):

    CurrentVideoNumber = 0 #The index of the current video in the playlist
    VideoList = Playlist(PlaylistLink) #Defines playlist object

    #Gets link of each video
    for VideoLink in VideoList.video_urls:

        #Make video object for current url
        try:
            Video = YouTube(VideoLink, use_oauth=True, allow_oauth_cache=True)

        #Prevents total program error if video is not available
        except exceptions.VideoUnavailable:
            print(f'Video {VideoLink} is unavaialable, skipping.')
            continue
        
        #Download current video
        else:
            try:
                Title = Video.title
            except:
                Title = "N/A"

            CurrentVideoNumber += 1 #Changes old video index to the current one
            print(f'Downloading video: {Title}') #Tells user that current video has begun download

            #Get stream
            Streams = Video.streams.filter(file_extension='mp4', only_audio=True).last()

            #Download video from stream
            Streams.download(output_path=f"{root_dir}/Playlist downloader")
            print(f"{CurrentVideoNumber} of {len(VideoList.video_urls)} is complete...") #Tells user that current video download is complete

def ConvertVideoToAudio():

    FileList = os.listdir(f"{root_dir}/Playlist downloader")
    for File in FileList:
        FileName, FileExtension = os.path.splitext(File)

        #Ignore python file
        if ".py" in File:
            continue
        '''
        if ".mp4" in File:
            print(FileName)
            newname = FileName + ".mp3"
            os.rename(File, newname)
        '''
        
        #Give location of Mp4 and future Mp3
        Mp4 = rf"{root_dir}/Playlist downloader/{FileName}.mp4"
        Mp3 = rf"{root_dir}/Playlist downloader/{FileName}.mp3"

        #Make audio and video object
        Video = VideoFileClip(Mp4)
        Audio = Video.audio

        #Write audio data in mp3 file
        Audio.write_audiofile(Mp3) 
        Video.close()
        Audio.close()

        #Ignore mp3 file and discard mp4
        if FileExtension == ".mp3":
            continue
        else:
            os.remove(Mp4)

#Downloads single video or playlist depending on user input
if DownloadType == "v":
    if DesiredFileFormat == "mp4":
        LinkInput = input("Type the link of the video you'd like to download here --> ")
        DownloadVideo(LinkInput)
    elif DesiredFileFormat == "mp3":
        LinkInput = input("Type the link of the video you'd like to download here --> ")
        DownloadVideo(LinkInput)

elif DownloadType == "p":
    if DesiredFileFormat == "mp4":
        LinkInput = input("Type the link of the playlist you'd like to download here --> ")
        DownloadPlaylist(LinkInput)
    elif DesiredFileFormat == "mp3":
        LinkInput = input("Type the link of the playlist you'd like to download here --> ")
        DownloadPlaylist(LinkInput)
print("Standby...")

#Converts the file to mp3 if user specifies mp3 type
if DesiredFileFormat == "mp3":
    print("Converting to mp3...")
    time.sleep(2)
    ConvertVideoToAudio()
    print("Done!")
    time.sleep(2)

我尝试使用 pytube 库的示例程序来查看是否能够在我的设备上下载视频,但它也返回了相同的错误,所以我确信问题与程序本身无关。

python youtube urllib pytube
1个回答
0
投票

我也有同样的问题。不过我升级了pytube之后问题就解决了。

删除旧的 pytube:

pip uninstall pytube

安装最新版本:

pip install pytube
© www.soinside.com 2019 - 2024. All rights reserved.