开发者

Ignore exception/error in Python while using YouTube API

开发者 https://www.devze.com 2023-02-20 09:34 出处:网络
I am using Python YouTube API to retrieve information from a few video ids. I sometimes run into a gdata.service.RequestError: {\'status\':

I am using Python YouTube API to retrieve information from a few video ids. I sometimes run into a

gdata.service.RequestError: {'status': 403, 'body': 'Private video', 'reason': 'Forbidden'}

However, I would like my program to ignore the error and continue. PFB some code snippet:

@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()


The exceptions were in the lines :

entry = yt_service.GetYouTubeVideoEntry(video_id = entry_video_id)

and

comment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url)

I added the exception_ignore_handler and the program runs by ignoring the exception now.

0

精彩评论

暂无评论...
验证码 换一张
取 消