I am a very beginner Python user. I am attempting to collect all comments from a YouTube video using the YouTube V3 API. My code is only giving me top level comments, and not replies. This is my first time using the YouTube API and I do not believe I have exceeded any quotas or rate limits.
My code is below. I have been inserting the API key and video ID in the appropriate place and still only receiving top level comments. I would appreciate any assistance as to where I may be going wrong. Thanks in advance!
import osimport csvimport googleapiclient.discovery# Set your API key hereAPI_KEY = 'API KEY'# Initialize the YouTube API clientyoutube = googleapiclient.discovery.build('youtube', 'v3', developerKey=API_KEY)def get_all_comments(video_id): all_comments = [] # Call the YouTube API to retrieve all comments (including replies) next_page_token = None while True: response = youtube.commentThreads().list( part='snippet', videoId=video_id, textFormat='plainText', pageToken=next_page_token ).execute() for item in response['items']: comment_data = item['snippet']['topLevelComment']['snippet'] comment_data['authorDisplayName'] = comment_data['authorDisplayName'] # Username or Display Name comment_data['authorChannelId'] = comment_data.get('authorChannelId', {}).get('value', None) # Channel ID (if available) all_comments.append(comment_data) # Collect replies to the top-level comment if 'replies' in item: for reply_item in item['replies']['comments']: reply_data = reply_item['snippet'] reply_data['authorDisplayName'] = reply_data['authorDisplayName'] # Username or Display Name reply_data['authorChannelId'] = reply_data.get('authorChannelId', {}).get('value', None) # Channel ID (if available) all_comments.append(reply_data) # Check if there are more comments to retrieve if 'nextPageToken' in response: next_page_token = response['nextPageToken'] else: break return all_commentsdef save_comments_to_csv(comments, file_path): with open(file_path, 'w', encoding='utf-8', newline='') as csvfile: fieldnames = comments[0].keys() # Use the keys from the first comment as fieldnames csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames) csv_writer.writeheader() for comment in comments: csv_writer.writerow(comment)if __name__ == "__main__": video_id = 'video_id' comments = get_all_comments(video_id) custom_location = 'Test Test Custom Path' save_comments_to_csv(comments, custom_location) print(f"Total comments collected: {len(comments)}") print(f"Comments saved to '{custom_location}'")