DEV Community

frankxie
frankxie

Posted on

Export YouTube Comments to CSV for Sentiment Analysis (Python, pandas and VADER)

YouTube comments are one of the best sources of unfiltered opinion on the internet. Under a product review you'll find owners describing what they like, buyers explaining why they returned it, and people asking the questions your FAQ should answer. For a brand, a product team or an NLP project, that's useful text, as long as you can get it out of YouTube and into a table.

The official route is the YouTube Data API. It can do this: commentThreads.list returns comments 100 at a time. But you need a Google Cloud project and an API key, you write the paging yourself, and a thread response doesn't always include every reply, so full threads need a second endpoint (comments.list). That's fine for a long-term pipeline and a lot of setup for "I want the comments of these five videos in a spreadsheet".

This tutorial uses an Apify Actor that exports comments to JSON, CSV or Excel with no API key, then scores them with a simple sentiment model in pandas. It also shows where that model gets things wrong, because it does.

Disclosure: I built and maintain this Actor. It is a paid tool ($1.00 per 1,000 results). I've tried to describe what it can't do as plainly as what it can.

What you can do with the data

  • Product sentiment. Pull the comments of the main review videos for a product and measure how positive they are overall, and about specific things like battery or camera.
  • Find complaints and questions. Sort by sentiment or search for "?" to find what people are unhappy about or confused by.
  • Monitor a video after launch. Sort by newest and run it on a schedule to see the reaction as it comes in.
  • Build a text dataset. Each comment has its like count, reply count and a direct link, which makes labeling and sampling easier.

Step 1: Set up a run in Apify Console

Open YouTube Comments Scraper and click Try for free. The input form has these fields:

Field What it does
Video URLs (videoUrls) Video links, youtu.be links, Shorts links or 11-character video IDs.
Max results (maxItems) Upper limit for the whole run, comments and replies together. Default 100.
Max comments per video (maxItemsPerQuery) Stops one popular video from using up the run. Replies count too.
Sort comments by (commentSort) top (the order YouTube shows) or newest.
Include replies (includeReplies) Off by default. When on, each reply is saved as its own row with parentCommentId pointing to the comment.

No API key, login or proxy is needed.

Step 2: Run it and export

Click Start. When the run finishes, open the Output tab and export as JSON, CSV or Excel.

For this article I used a popular iPhone 17 review video and asked for 30 top comments without replies:

{
  "videoUrls": ["https://www.youtube.com/watch?v=rng_yUSwrgU"],
  "commentSort": "top",
  "includeReplies": false,
  "maxItems": 30
}
Enter fullscreen mode Exit fullscreen mode

It saved 30 comments in about 5 seconds. Here are two. I removed videoUrl and the author fields (name, channel ID, channel URL and avatar); the other values are unchanged:

[
  {
    "type": "comment",
    "commentId": "UgwgPkuIFOb0aVkSmiZ4AaABAg",
    "commentUrl": "https://www.youtube.com/watch?v=rng_yUSwrgU&lc=UgwgPkuIFOb0aVkSmiZ4AaABAg",
    "videoId": "rng_yUSwrgU",
    "videoTitle": "iPhone 17 Review: No Asterisks!",
    "isReply": false,
    "parentCommentId": null,
    "text": "The wife and I just went from the iPhone 8plus to the base 17 and we couldn’t be happier!",
    "likeCount": 8100,
    "likeCountText": "8.1K",
    "replyCount": 121,
    "publishedTimeText": "1 year ago",
    "publishedAtEstimated": "2025-11-02T13:29:23Z",
    "isEdited": false,
    "isPinned": false,
    "isHeartedByCreator": false,
    "authorIsVerified": false,
    "authorIsVideoOwner": false,
    "scrapedAt": "2026-11-02T13:29:23Z"
  },
  {
    "type": "comment",
    "commentId": "Ugy2qYiCTgV6qosGfMx4AaABAg",
    "commentUrl": "https://www.youtube.com/watch?v=rng_yUSwrgU&lc=Ugy2qYiCTgV6qosGfMx4AaABAg",
    "videoId": "rng_yUSwrgU",
    "videoTitle": "iPhone 17 Review: No Asterisks!",
    "isReply": false,
    "parentCommentId": null,
    "text": "I bought my iPhone 17 base line few days ago. Upgraded from 12 Pro and couldn't be happier with my decision.",
    "likeCount": 33,
    "likeCountText": "33",
    "replyCount": 1,
    "publishedTimeText": "7 months ago",
    "publishedAtEstimated": "2026-04-06T13:29:23Z",
    "isEdited": false,
    "isPinned": false,
    "isHeartedByCreator": false,
    "authorIsVerified": false,
    "authorIsVideoOwner": false,
    "scrapedAt": "2026-11-02T13:29:23Z"
  }
]
Enter fullscreen mode Exit fullscreen mode

Look at the dates. publishedAtEstimated is calculated from YouTube's relative text, so "1 year ago" becomes exactly one year before the scrape. In this sample, 26 of the 30 top comments said "1 year ago", so they all got the same date. For a time series, use newest-first runs on a schedule rather than the dates of old top comments.

A note on replies: I first ran the same video with includeReplies: true. The Actor saves each comment's replies right after the comment, and the first comment had 62 replies, so 29 of my 30 rows were replies to that one comment. If you want replies, give the run a larger maxItems.

Step 3: Sentiment analysis in Python

Install the client, pandas and VADER, a small rule-based sentiment model that works without a GPU:

pip install apify-client pandas vaderSentiment
Enter fullscreen mode Exit fullscreen mode
from apify_client import ApifyClient
import pandas as pd
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

client = ApifyClient("YOUR_APIFY_TOKEN")

run = client.actor("pipiagent/youtube-comments-scraper").call(run_input={
    "videoUrls": [
        "https://www.youtube.com/watch?v=rng_yUSwrgU",
        # add more review videos of the same product here
    ],
    "commentSort": "top",
    "includeReplies": False,
    "maxItemsPerQuery": 1000,
    "maxItems": 5000,
})
df = pd.DataFrame(client.dataset(run.default_dataset_id).iterate_items())

analyzer = SentimentIntensityAnalyzer()
df["sentiment"] = df["text"].map(lambda t: analyzer.polarity_scores(t)["compound"])
df["label"] = pd.cut(df["sentiment"], [-1, -0.05, 0.05, 1],
                     labels=["negative", "neutral", "positive"], include_lowest=True)

print(df["label"].value_counts())
# Weighted by likes: how much the audience agrees with each side
print(df.groupby("label", observed=True)["likeCount"].sum())

# Sentiment about specific topics
ASPECTS = {"battery": r"battery", "camera": r"camera", "screen": r"screen|display",
           "price": r"price|expensive|cheap|afford"}
rows = []
for name, pattern in ASPECTS.items():
    hit = df["text"].str.contains(pattern, case=False, regex=True)
    rows.append({"aspect": name, "comments": int(hit.sum()),
                 "avg_sentiment": round(df.loc[hit, "sentiment"].mean(), 2)})
print(pd.DataFrame(rows))

# Always read the extremes yourself
print(df.nsmallest(10, "sentiment")[["sentiment", "likeCount", "text"]])
df.to_csv("comments_with_sentiment.csv", index=False)
Enter fullscreen mode Exit fullscreen mode

The -0.05 and 0.05 cut-offs are the usual thresholds for VADER's compound score.

I ran this on the 30 comments from my test. VADER labeled 21 positive, 4 neutral and 5 negative. Then I read the 5 negative ones. One said "Intro was fire" with a fire emoji, which VADER reads as negative. Another was the "couldn't be happier with my decision" comment above, which it scored at -0.42. A third was someone saying they'd miss their old iPhone 12 mini after trading it in for a 17, which is closer to nostalgic than negative. So at least two of the five were clearly wrong.

That's typical for word-list models on social media text: slang and phrases like "couldn't be happier" trip them up. VADER is fine for a first pass on thousands of comments and for comparing videos with each other. If the numbers matter, label a sample by hand to measure the error, or try a transformer model trained on social media text, which is slower but usually handles this kind of phrasing better.

What it costs

You pay per saved result: $1.00 per 1,000 comments, with no start fee and no monthly rental. A reply counts as one result.

  • My 30-comment test: $0.03.
  • 1,000 top comments from each of 5 review videos: $5.00.
  • 3,000 comments with replies: $3.00.

You can also set a maximum charge per run in the run options, and the Actor stops when it reaches that amount.

Limitations

  • Like counts are rounded by YouTube. "8.1K" becomes 8100, so likeCount is approximate for popular comments.
  • Dates are estimates from text like "1 year ago", as described above. The original text is kept in publishedTimeText.
  • Replies come in thread order. With replies on, a busy thread can use up a small maxItems before the run reaches the next comment.
  • Large comment sections take time. YouTube sends about 20 comments per page, so 10,000 comments take a few minutes.
  • Videos with comments turned off are skipped with a warning, as are private and deleted videos.
  • Personal data. Results include public usernames and channel links. If you store them, make sure you have a legitimate reason under GDPR or similar laws, or drop those columns as I did above.

Related tools

To build the list of videos first, YouTube Search Scraper finds videos by keyword with upload-date filters and sort by views. If your product is an app, Google Play Reviews Scraper exports app reviews with star ratings, which give you a label to check your sentiment model against.

You can try it on any video from the YouTube Comments Scraper store page. If something doesn't work the way this article says, open an issue there and I'll look into it.

Top comments (0)