我正在使用Python YouTube API从一些视频ID中检索信息。我有时碰到了
gdata.service.RequestError:{'status': 403,'body':'私人视频', 'reason':'禁止'}
但是,我希望我的程序忽略错误并继续。 PFB的一些代码片段:
@contextlib.contextmanager
def exception_ignore_handler():
try:
yield
except Exception:
pass
''' Get Video details '''
def WriteStatEntryDetails(entry_video_id,data_file):
entry = yt_service.GetYouTubeVideoEntry(video_id = entry_video_id)
with exception_ignore_handler():
author = entry.author[0].name.text
data_file.write(author)
data_file.write(",")
with exception_ignore_handler():
time = entry.published.text
data_file.write(time)
data_file.write(",")
with exception_ignore_handler():
category = entry.media.category[0].label
data_file.write(category)
data_file.write(",")
with exception_ignore_handler():
duration = entry.media.duration.seconds
data_file.write(duration)
data_file.write(",")
with exception_ignore_handler():
view_count = entry.statistics.view_count
data_file.write(view_count.rstrip())
data_file.write(",")
with exception_ignore_handler():
rating = entry.rating.average
data_file.write(rating.rstrip())
data_file.write(",")
''' Get the comment feed of a video given a entry_video_id'''
def WriteStatCommentFeed(entry_video_id, data_file):
url = comment_feed_url % entry_video_id
comment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url)
try :
numComments = comment_feed.total_results.text
data_file.write(numComments)
except:
pass
''' Populate data statistics '''
def populate_data_stats(positive_video_id_list):
data_file = open(data_statistics_file, "w")
for entry_video_id in positive_video_id_list :
data_file.write(entry_video_id)
data_file.write(",")
WriteStatEntryDetails(entry_video_id, data_file)
WriteStatCommentFeed(entry_video_id, data_file)
data_file.write("\n")
data_file.close()
答案 0 :(得分:0)
例外情况如下:
entry = yt_service.GetYouTubeVideoEntry(video_id = entry_video_id)
和
comment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url)
我添加了exception_ignore_handler,程序现在通过忽略异常来运行。