Glasser Team5 min read
How to Export YouTube Comments with an Agent or Python
Collect a bounded YouTube comment sample, preserve identifiers and understand pagination, replies and unavailable videos.

Choose a collection path and a sample limit
You can export YouTube comments by collecting records for a video and writing the returned fields to a CSV. Decide whether you need top-level comments, replies or a phrase search before selecting the source.
For a workflow inside your agent, start with the YouTube Comments Exporter. Connect Glasser, provide the video URL and ask the agent to inspect comment ordering, pagination, reply coverage and cost. The agent can then prepare an export using its file tools.
If you want to maintain your own Python integration, Google's YouTube Data API provides a documented comment-thread endpoint. That route requires a Google project with the API enabled, a suitable API key and available quota. The example below uses Google directly; it is not a Glasser Python SDK.
In either route, record a maximum count. A bounded collection is easier to review than an open-ended request for “all comments,” especially when a video receives new comments while collection is running.
Define the export before running it
Keep a stable comment identifier, the video identifier and original text. Add author and publication time when returned. When collecting replies, retain the parent identifier.
For Glasser, use the setup guide, then describe the task:
Collect a bounded comment sample from these YouTube video URLs.
Inspect the Glasser source's current contract and cost first.
Ask me to confirm ordering, maximum count and whether replies matter.
Keep original text, video ID, comment ID, author and published time
when returned. Preserve pagination and reply-coverage limitations.
Write a CSV with one row per comment and a separate collection log.
Stop at the agreed budget and retain unsuccessful videos in the log.
The YouTube MCP Server directory covers source discovery. Your agent should inspect the chosen operation rather than assume it uses the same inputs as Google's API.
Export top-level comments with Python
Google's commentThreads.list reference documents videoId, maxResults, pageToken, order and textFormat. maxResults accepts up to 100 records per page. The example uses two pages at most, so it is deliberately bounded.
Set YOUTUBE_API_KEY in your local environment and YOUTUBE_VIDEO_ID to a video's identifier. Save this as export_comments.py and run it with Python 3. It uses only the standard library.
import csv
import json
import os
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import urlopen
def collect_comments(api_key, video_id, max_pages=2):
rows = {}
page_token = None
for page_number in range(max_pages):
params = {
"key": api_key,
"part": "snippet",
"videoId": video_id,
"maxResults": 100,
"order": "time",
"textFormat": "plainText",
}
if page_token:
params["pageToken"] = page_token
url = "https://www.googleapis.com/youtube/v3/commentThreads?"
try:
with urlopen(url + urlencode(params), timeout=30) as response:
payload = json.load(response)
except HTTPError as error:
raise RuntimeError(
f"YouTube returned HTTP {error.code}; inspect access and quota."
) from None
for thread in payload.get("items", []):
comment = thread["snippet"]["topLevelComment"]
snippet = comment["snippet"]
rows[comment["id"]] = {
"video_id": video_id,
"comment_id": comment["id"],
"author": snippet.get("authorDisplayName", ""),
"text": snippet.get("textDisplay", ""),
"published_at": snippet.get("publishedAt", ""),
}
page_token = payload.get("nextPageToken")
if not page_token:
break
return list(rows.values()), bool(page_token)
def spreadsheet_text(value):
if value.lstrip().startswith(("=", "+", "-", "@")):
return "'" + value
return value
if __name__ == "__main__":
comments, has_more = collect_comments(
os.environ["YOUTUBE_API_KEY"], os.environ["YOUTUBE_VIDEO_ID"]
)
with open("youtube-comments.csv", "w", newline="", encoding="utf-8") as target:
writer = csv.DictWriter(
target,
fieldnames=["video_id", "comment_id", "author", "text", "published_at"],
)
writer.writeheader()
writer.writerows(
{key: spreadsheet_text(value) for key, value in row.items()}
for row in comments
)
print({"exported": len(comments), "more_pages_available": has_more})
The spreadsheet guard prefixes formula-like text for safer opening in a spreadsheet. Retain the raw JSON separately if you need byte-for-byte source preservation. The guard is local export logic, not a YouTube or Glasser feature.
The collector deduplicates by comment ID. more_pages_available: true means the page cap stopped collection while a further page token remained. It does not tell you how many comments are still available.
Handle replies, errors and search scope
The example exports top-level comments only. Google's comments.list reference supports retrieving replies with a parentId. A comment-thread response can contain only a subset of replies; collecting all available replies requires a separate paginated step.
If comments are disabled, the API can return commentsDisabled. An unavailable video, an invalid key or exhausted quota also needs attention. Record the failure and inspect its cause before retrying; do not silently turn the error into a zero-comment result.
For phrase research, use the YouTube Comment Finder to prepare a search within selected videos and retrieved comments. Google also documents a searchTerms parameter, but server-filtered results and an unfiltered export describe different samples.
Your personal YouTube comment history is a separate account task. Neither a public video's export nor a keyword search establishes everywhere a particular person has commented.
Review the sample and reuse the workflow
Keep the collection date, ordering, page cap and reply policy beside the file. When comparing videos, use equivalent collection rules and preserve the video identifier on every row.
This guide was checked against Google's official references on November 20, 2026. The Python collection logic was tested with offline fixtures for pagination, deduplication, empty responses and errors. No authenticated Google request or paid Glasser collection was performed.
Can I download every comment?
The example stops after two pages and excludes replies. Wider collection needs an explicit scope, available quota and pagination; report actual coverage.
Can I export without writing code?
Use the tool's prompt with a file-capable agent connected to Glasser. Inspect the selected source and agree on count and cost before collection.
Related posts
View more
阅读约 5 分钟
How to Copy and Export Instagram Comments
Choose between saving one Instagram comment and exporting a bounded comment sample with authors, replies and source context.

阅读约 10 分钟
How to Get YouTube Transcripts: Access Options and Agent Workflows
Compare ways to get YouTube transcripts, then use Glasser with your agent to turn video text into notes, research evidence, or a custom report with usage-based data costs.
Make your agent
work with real data.
Search, inspect, and run data APIs through one Glasser key. Turn your next question into a result you can use.
Get started with Glasser