来自 Youtube API Data V3 的错误即使在使用 Try and except 后也会中断我的脚本

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

我正在尝试专门使用 Youtube API:Youtube API Data V3 从某个频道的所有视频中获取评论。当视频上的评论被禁用时,我收到一个错误,我试图让我的代码忽略它并继续处理其他视频。

我遇到的错误:

<HttpError 403 when requesting https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Csnippet%2Creplies&maxResults=5&order=relevance&videoId=4Tcsg6tU3ow&key=AIzaSyAPFiPIYO4oIRSyPTEUjPl7XGJYte-JkfI&alt=json returned "The video identified by the <code><a href="/youtube/v3/docs/commentThreads/list#videoId">videoId</a></code> parameter has disabled comments.". Details: "[{'message': 'The video identified by the <code><a href="/youtube/v3/docs/commentThreads/list#videoId">videoId</a></code> parameter has disabled comments.', 'domain': 'youtube.commentThread', 'reason': 'commentsDisabled', 'location': 'videoId', 'locationType': 'parameter'}]">

这是预期的,但是我正在使用 except 中的代码块来让程序忽略此 videoId,但是当遇到此错误时程序会被中断。此外,我遇到过这样的情况:它将转到此 videoId,打印错误并忽略它,然后重新访问 videoID 并中断脚本,即使 videoId 现在位于processed_video_ids 中并且不应再次运行。

这是我认为在这种情况下很重要的代码片段:

for video_id in videoMetadata:
        videoId = video_id['videoId']
        publish_date = dt.strptime(video_id['publish_date'], "%Y-%m-%dT%H:%M:%SZ")
        if videoId not in processed_video_ids:
            try:
                print(f"Processing comments for video ID: {videoId}")
                comment_threads(videoId, to_csv=True)

               # Block of Code for file moving Removed
                
            except requests.exceptions.HTTPError as e:
            # Check if the exception is due to a 403 error (Forbidden or Disabled Comments)
                if e.response.status_code == 403:
                    error_message = e.response.json()["error"]["errors"][0]['reason']
                    if error_message == 'commentsDisabled':
                        print("Comments are disabled for this video. Skipping this request.")
                        
                    else:
                        print(f"403 Forbidden: {error_message}. Skipping this request.")
                        
                    
                else:
                    # Handle other HTTP errors
                    print(f"HTTP error occurred: {e}")
                    

            except requests.exceptions.RequestException as e:
                # Handle other exceptions (e.g., network errors)
                print(f"Error making API request: {e}")
                

        processed_video_ids.add(videoId)

此外,我的脚本在遇到错误时似乎从未打印字符串,这可能会让我相信我的脚本在访问 API 提供的错误消息时是错误的。

python error-handling youtube-data-api interrupted-exception
1个回答
0
投票

找到解决方案。 Google API 有自己的请求错误的方式,因此可以使用:

except requests.exceptions.HTTPError as e:

是:

except googleapiclient.errors.HttpError as e:
try:
    error_content = e.content.decode('utf-8')
    error_data = json.loads(error_content)

您可以使用以下命令查看错误代码:

error.resp.status == 'ERROR CODE HERE'
© www.soinside.com 2019 - 2024. All rights reserved.