[Python] Analysing YouTube comments using Python -- parameter has disabled comments

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to get into text analysis using YouTube comments. I've been using the code from the following website to scrape YouTube:

    https://www.pingshiuanchua.com/blog/post/using-youtube-api-to-analyse-youtube-comments-on-python

    The script starts working, but there is a section of the code that generates an error if comments have been disabled, and I can't find a way to check to see if comments are disabled or if comments exist, and to just skip that video if there are no comments to scrape, and continue on to the next video.

    The code chunk in question creating the error is:

    # =============================================================================
    # Get Comments of Top Videos
    # =============================================================================

    video_id_pop = []
    channel_pop = []
    video_title_pop = []
    video_desc_pop = []
    comments_pop = []
    comment_id_pop = []
    reply_count_pop = []
    like_count_pop = []

    from tqdm import tqdm

    for i, video in enumerate(tqdm(video_id, ncols = 100)):
    response = service.commentThreads().list(
    part = 'snippet',
    videoId = video,
    maxResults = 100, # Only take top 100 comments...
    order = 'relevance', #... ranked on relevance
    textFormat = 'plainText',
    ).execute()

    comments_temp = []
    comment_id_temp = []
    reply_count_temp = []
    like_count_temp = []
    for item in response['items']:
    comments_temp.append(item['snippet']['topLevelComment']['snippet']['textDisplay'])
    comment_id_temp.append(item['snippet']['topLevelComment']['id'])
    reply_count_temp.append(item['snippet']['totalReplyCount'])
    like_count_temp.append(item['snippet']['topLevelComment']['snippet']['likeCount'])
    comments_pop.extend(comments_temp)
    comment_id_pop.extend(comment_id_temp)
    reply_count_pop.extend(reply_count_temp)
    like_count_pop.extend(like_count_temp)

    video_id_pop.extend([video_id]*len(comments_temp))
    channel_pop.extend([channel]*len(comments_temp))
    video_title_pop.extend([video_title]*len(comments_temp))
    video_desc_pop.extend([video_desc]*len(comments_temp))

    query_pop = [query] * len(video_id_pop)


    Edited to add:

    The person who created the code left a message to fix the error saying:

    "You can wrap the query part of the code in a try...except statement, where if the try statement (the query part) failed, you can push an except of blank response or "error" string into the list."

    I have NFI how to carry this out if it makes sense to anyone else...

    Continue reading...

Compartilhe esta Página