DEV Community

Aurelix Solutions
Aurelix Solutions

Posted on

YouTube comments and replies in Python, with likes, pinned and hearted flags, no login

Creators, brand teams and researchers keep coming back to the same place: the comments under a video. What do viewers ask for, what do they complain about, which comment did the creator pin or heart, and what did people say since yesterday. Scrolling a busy video by hand stops working after a few hundred comments, and replies make it worse.

This post reads YouTube comments and replies into Python from video links or a channel's latest uploads, sorts them by likes, rebuilds the reply threads, and sets up a daily feed of only the new comments.

Disclosure: I'm Aurelix, and I built YouTube Comments Scraper, the tool used here. It's a paid tool (prices below).

What each row holds

One row per comment or reply, 27 fields:

  • status (ok, or why a video returned nothing: no_comments, comments_off, unavailable, not_found and others), error, input.
  • videoId, videoUrl, videoTitle, videoCommentCount (the total YouTube shows, replies included).
  • commentId, url (a direct link to the comment), text.
  • authorName, authorChannelId, authorChannelUrl, authorIsVerified, authorIsChannelOwner.
  • likeCount, likeCountText, replyCount, isReply, parentId, isPinned, isHearted, isEdited.
  • publishedTimeText as YouTube shows it ("3 days ago"), publishedAt as an ISO date worked out from it, and publishedAtPrecision.

Email addresses and phone numbers written in a comment are masked.

Comments from a list of videos

pip install apify-client
Enter fullscreen mode Exit fullscreen mode
import csv
import os

from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("aurelix/youtube-comments-scraper").call(
    run_input={
        "videos": [
            "https://www.youtube.com/watch?v=jNQXAC9IVRw",
            "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
        ],
        "maxCommentsPerVideo": 200,
        "sort": "top",
    }
)
rows = list(client.dataset(run["defaultDatasetId"]).iterate_items())
comments = [r for r in rows if r["status"] == "ok"]

fields = ["videoTitle", "authorName", "likeCount", "replyCount", "isPinned", "isHearted", "publishedAt", "text"]
with open("comments.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
    w.writeheader()
    w.writerows(comments)
Enter fullscreen mode Exit fullscreen mode

You get exactly the number you set per video, or every comment when the video has fewer. Video IDs, Shorts links and youtu.be links work too. A video with comments turned off, or one that is private or removed, gets a status row that says why instead of comments.

The most-liked comments, and what the creator pinned or hearted

for c in sorted(comments, key=lambda c: -(c["likeCount"] or 0))[:10]:
    flags = ("pinned " if c["isPinned"] else "") + ("hearted" if c["isHearted"] else "")
    print(f"{c['likeCountText'] or 0:>6} likes  {c['authorName']:20} {flags:15} {c['text'][:60]}")
Enter fullscreen mode Exit fullscreen mode

Like counts above 1,000 are rounded by YouTube (1.2K, 4.8M); likeCountText keeps the shown value.

Whole threads, with every reply linked to its comment

Turn on includeReplies and each reply becomes its own row with isReply true and parentId set, right after the comment it answers. Replies count toward maxCommentsPerVideo; maxRepliesPerComment caps busy threads.

from collections import defaultdict

run = client.actor("aurelix/youtube-comments-scraper").call(
    run_input={"videos": ["https://www.youtube.com/watch?v=jNQXAC9IVRw"], "maxCommentsPerVideo": 1000,
               "includeReplies": True, "maxRepliesPerComment": 20}
)
rows = [r for r in client.dataset(run["defaultDatasetId"]).iterate_items() if r["status"] == "ok"]

replies = defaultdict(list)
for r in rows:
    if r["isReply"]:
        replies[r["parentId"]].append(r)

for c in (r for r in rows if not r["isReply"]):
    print(f"{c['authorName']}: {c['text'][:70]}")
    for r in replies[c["commentId"]][:3]:
        print(f"    {r['authorName']}: {r['text'][:66]}")
Enter fullscreen mode Exit fullscreen mode

A channel's latest videos instead of links

run_input = {"channels": ["@mkbhd"], "maxVideosPerChannel": 3, "maxCommentsPerVideo": 300, "sort": "newest"}
Enter fullscreen mode Exit fullscreen mode

Channel links, @handles and channel IDs work. Each channel contributes its newest maxVideosPerChannel uploads.

Only new comments, every morning

run_input = {
    "channels": ["@mkbhd"],
    "maxVideosPerChannel": 5,
    "sort": "newest",
    "incremental": True,
    "stateKey": "mkbhd-comments-daily",
    "slackWebhookUrl": "https://hooks.slack.com/services/...",
}
Enter fullscreen mode Exit fullscreen mode

The first run returns every comment up to your limit and remembers them. Each later run returns only comments earlier runs did not return; a video with nothing new costs $0.0001, and the first 10 such videos in a run are free. Keep stateKey set so the memory stays the same while you change the input. Save the input as a task in the Apify Console and schedule it daily: Slack gets a short digest, and nothing is sent when nothing is new.

Why this tool

  • Exactly the number of comments you ask for per video, or every comment the video has.
  • Replies as their own rows, each linked to its parent comment.
  • Pinned, creator-heart and edited flags on every row.
  • An only-new mode with a Slack or webhook digest, and empty videos that cost almost nothing.

Limits

  • What a logged-out visitor sees: members-only and age-restricted videos are skipped with a status row.
  • publishedAt comes from YouTube's rounded age label ("2 years ago"), so it is only as precise as that label says in publishedAtPrecision.
  • YouTube's total comment count includes replies and comments it holds back, so a video can list fewer comments than its total.
  • No dislike counts, commenter subscriber counts or live chat.
  • If YouTube refuses the run, it stops with a BLOCKED status and charges only for what it returned.

Cost

$0.40 per 1,000 comments on Apify's free plan, from $0.30 per 1,000 on paid plans, plus a $0.001 start fee per run; replies are charged like comments. The current prices are on the Store page; Apify's free plan includes $5 of credit a month, about 12,000 comments.

Use it from an AI assistant

The tool also works through Apify's hosted MCP server, so Claude, ChatGPT or Cursor can run it from a request like "get the 500 newest comments on this YouTube video and summarise what viewers ask for most". Server URL: https://mcp.apify.com/?tools=aurelix/youtube-comments-scraper.

Links

Top comments (0)