Ti è stato utile?
How to Scrape YouTube
Technical engineer
YouTube is the largest video platform there is, and people scrape it for comments, video stats and search results. It's also one of the few big sites where you usually don't need a headless browser at all. YouTube's own front end gets its data from an internal API called Innertube, and a scraper can call the same endpoints directly over plain HTTPS.
There are still a few things to get right. Comments come in pages chained together by continuation tokens, so you can't jump to page 30 or split one video between workers. Some numbers YouTube shows are rounded on purpose, and comment dates are only relative ("1 year ago"). And if a site ever starts refusing you, you want the scraper to notice instead of quietly writing empty files.
This guide uses the open-source YouTube scraper from the 2scraper project to collect comments, replies, video metadata and search results into JSON or CSV. The figures come from the project's README, changelog and troubleshooting notes, each with the date it was measured.
What you get
The scraper has three modes:
| Mode | What it returns | Typical use |
|---|---|---|
| comments (default) | Comment threads of one video, optionally with replies | Sentiment analysis, audience research |
| video | One video's metadata, including the exact upload date, duration, category and keywords | Channel and content monitoring |
| search | Videos for a search query | Finding videos to feed into comments mode |
A comment row has sku (the comment id), title (the video's title, repeated so a big CSV reads without a join), video_id, text, author_name, author_channel_id, author_is_verified, like_count and like_count_text, reply_count, published_time_text, published_at_approx, published_at_precision, edited, reply_level, parent_id, is_pinned, pinned_by, creator_hearted and sort.
A reply's id contains its parent's id, separated by a dot. That's how parent_id is filled, and it means you can rebuild the comment tree without any extra bookkeeping.
Before you start: do you need the official API?
It's worth asking first, and the repository's README asks it too. The YouTube Data API method commentThreads.list costs 1 quota unit per call and returns up to 100 comments. The default allocation is 10,000 units a day, so that's roughly a million comments a day, free, with a Google account.
The official API also gives you two things the scraper can't. On the web, YouTube only shows comment likes rounded ("318K") and comment dates as relative text ("1 year ago"). That was checked on 70 comments in four captures under three different Innertube clients, and there was nothing more precise anywhere in the payload. Video rows are different: their like count and upload date are exact.
The scraper makes sense when you don't want an account or a quota ceiling, when you want to choose which of YouTube's two orderings you sample, or when you need fields the official API doesn't expose, such as pinned, creator-hearted, verified and the sort a row came from.
What you need
Python 3.9 to 3.13. For the default setup that's it: no browser, no proxy, no key.
On 2026-09-21 the scraper ran from a bare datacentre address in Finland with no API key, no proxy, no cookies and no account. It fetched 60 consecutive pages, 1,200 comments, with zero refusals, at about 0.25 s per page.
A browser engine (Playwright, Selenium or pyppeteer) is optional. You install one only if you want a fallback for the day YouTube starts refusing plain HTTPS, or if you want to drive a browser on purpose.
Installation
bash
git clone https://github.com/2scraper/youtube-scraper.git
cd youtube-scraper
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt
That installs no browser library. If you want the browser fallback, add an engine in the same environment:
bash
pip install -r requirements-playwright.txt
playwright install chromium
Install only one engine per virtual environment. Playwright and pyppeteer need different versions of pyee, and pyppeteer and Selenium clash on urllib3, so pip ends up quietly downgrading something.
Keys and proxies go in .env (TWOCAPTCHA_KEY, YOUTUBE_PROXY, YOUTUBE_CDP_ENDPOINT). You won't need any of them for a normal run. python3 env_config.py shows what was picked up without printing the values.
First run
bash
# Comments: 3 pages, newest first, with replies
python3 youtube_scraper.py --url dQw4w9WgXcQ --pages 3 --sort newest --replies
# Video metadata
python3 youtube_scraper.py --url dQw4w9WgXcQ --mode video
# Search, to find videos for comments mode
python3 youtube_scraper.py --url "web scraping tutorial" --mode search --pages 3
--url takes a video id or a full watch link, and in search mode it takes the query. By default you get one page of top comments in youtube_comments.json. A run prints something like this:
Page 1: 20 comments (20 total so far)
Page 2: 20 comments (40 total so far)
Page 3: 20 comments (60 total so far)
Collected 60 of the video's 2,457,616 comments (0.0024%). A run that fetched
every page it asked for is COMPLETE; it is not exhaustive.
[+] Saved 60 rows -> youtube_comments.json
A page here is a portion of data, not a screen. One page of top-level comments holds 20, and one page of replies holds 10. --replies costs an extra request for every thread that has replies, so about 20 more requests per page. A one-page run with --replies returned 192 rows from 20 threads on 2026-09-21.
How the scraper works
Transports
The main script, youtube_scraper.py, talks to Innertube over HTTPS. The --transport flag decides when a browser gets involved:
| Transport | What it does | Time for 2 pages (2026-09-22) |
|---|---|---|
| auto (default) | Plain HTTPS. Starts a browser only if a response looks like a challenge, then stays on it for the rest of the run | 2.0 s |
| http | Plain HTTPS only. If refused, it reports the refusal and stops | 2.0 s |
| browser | Always drives a browser | 3.4 s |
The rows were identical on all three. Once auto has switched to a browser it doesn't switch back, because a site that refused you once is likely to refuse again, and flipping back and forth would pay the browser start-up cost on every page.
Comments
The scraper sends the same POST /youtubei/v1/next request the YouTube page sends. Each response carries a continuation token for the next portion, and replies have their own tokens. Because each page is addressed by the previous one's token, a comments run is strictly sequential. If you pass --concurrency above 1 in comments mode, it's clamped to 1 with a warning saying why.
The two sort orders are two different samples, not the same comments reordered. top is YouTube's relevance ranking, the one the site shows by default, and newest is chronological. Every row records which one it came from in the sort column.
Video metadata
Video mode makes two calls per video. next returns the figures you see on the page, like views and likes. player adds the exact upload date, duration, category and keywords. This is the only mode where --concurrency above 1 helps, since every video has its own address.
Search
Search mode turns a query into a list of videos. Most people use it to collect video ids and then run comments mode on each one.
Blocks, captchas and paid options
YouTube rarely gets in the way. In the repository's tests, no challenge was ever shown to the scraper. The word recaptcha does appear once in a served page, but only in a CSS rule that hides a badge. YouTube's real defence is its own attestation system (bgChallenge), which isn't a captcha widget that any solver could handle.
The captcha code is still there as a safety net. With TWOCAPTCHA_KEY set, --solve-captcha decides when to pay: never, when-blocked (the default, which pays only for a page that's really gated) or always. A solved token needs a page to go into, so solving only works on the browser transport. With --transport http the scraper reports the refusal instead. Age-restricted, private and members-only videos are recognised separately and never trigger a paid solve, because there's nothing on those pages a solver could clear.
The paid products from 2Captcha are for volume and location. They help when you need many addresses, a specific country, or somewhere other than your own machine to run a browser.
Proxies. Use --proxy or --proxy-file, or put one in YOUTUBE_PROXY. By default one proxy is used for the whole run. With --proxy-rotate per-page the scraper builds a completely new session for each new address, rather than carrying cookies from one IP to another, which would look more suspicious than having no cookies. 2Captcha residential proxies work here; the Proxy API docs explain how to generate lists. Selenium can't use a proxy with a password and strips the credentials with a warning.
Browser API. 2Captcha Browser API works with the Playwright and pyppeteer engines through --cdp-endpoint. On 2026-09-21 a US profile returned comments, video metadata and search normally. The WebSocket connection was refused with HTTP 500 on one of three attempts made seconds apart, so the engines retry it. A profile_locked error isn't retried, since it means another run is using that profile. The Browser API's auto-solve extension adds captcha-looking markers such as cf-turnstile to every page it loads, even normal ones, so the scraper deliberately doesn't treat them as signs of a block. Selenium can't connect to a password-protected endpoint and refuses it by name. Setup is in the Browser API docs.
Scraper API. 2Captcha Scraper API returns a page's rendered HTML, and YouTube doesn't put comments in its HTML. It loads them with a separate POST request that the service doesn't make. On 2026-09-21 a request for the watch page came back with 0 comments, and waiting for the comment section timed out with HTTP 408. So scraper_api_client.py is used for video mode only, at $0.0005 per task. Since version 0.4.1 (October 16) it also reads the upload date, duration, category, keywords and exact like count from the player data embedded in the page.
Output files and exit codes
Each run writes the results (youtube_comments.json by default, or your --out name, as JSON, CSV or both) and a .meta.json file next to them. The sidecar records the status and, if something went wrong, exactly what: reply threads that didn't come back (reply_failures), video columns that are missing (videos_incomplete), and so on. A run counts as complete only if nothing failed, including reply threads and the second call in video mode.
If a run finds nothing, it writes nothing, so yesterday's good output isn't replaced with an empty list. Use --allow-empty if an empty result is what you want. Files are written atomically. In the CSV, cells starting with =, +, -, @, a tab or a line break get a leading apostrophe so Excel doesn't run them as formulas. That covers every author_name, since YouTube handles start with @.
| Code | Meaning |
|---|---|
| 0 | Complete |
| 1 | Crash, a bug in the scraper |
| 2 | Bad usage, e.g. --pages 0 or a negative --delay |
| 3 | Blocked |
| 4 | No comments, including comments turned off and deleted or private videos |
| 5 | Content never obtained, including a first page that was served but parsed to nothing |
| 6 | Partial: some pages, reply threads or video fields failed |
A few things look like bugs but aren't:
- Comments turned off is exit 4, not 3. YouTube answers with a normal-looking page, and it's a complete answer, so no proxy will help.
- total_comments can be approximate. The exact number only comes with the first page of the default top ordering. A newest run falls back to the rounded total ("2.4M").
- A long top run can see the same comment twice. The ranking changes while you scrape, and a comment that gains likes can be served again. The run logs and drops the duplicate.
- A locale other than English leaves two columns empty on purpose. In Russian, for example, the date and the rounded like count come back in Russian, and the parser returns null rather than guessing. The comment text isn't affected.
Comparing runs
bash
python3 diff_runs.py --old yesterday.json --new today.json
diff_runs.py compares two runs and shows what was added and what disappeared. It refuses pairs whose mode or sort differ, and pairs that aren't both complete, because pages a partial run didn't fetch would otherwise look like deleted comments.
A sample row
Here's the first row of the repository's sample_output.json, captured on 2026-09-21. The commenters in the sample are placeholders: names, channel ids, avatars and the text itself were rewritten, because republishing someone's comment is a separate act from YouTube showing it. Everything YouTube generates (counts, timestamps, flags, the video) is real.
json
{
"source": "youtube.com",
"scraped_at": "2026-09-21T08:43:43Z",
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ&lc=FIXTURE_CMT_1",
"sku": "FIXTURE_CMT_1",
"title": "Rick Astley - Never Gonna Give You Up (Official Video) (4K Remaster)",
"video_id": "dQw4w9WgXcQ",
"text": "fix turetex: tn otwri tten by ap",
"author_name": "@fixture_user_1",
"author_is_verified": true,
"like_count": 318000,
"like_count_text": "318K",
"reply_count": 962,
"published_time_text": "1 year ago",
"published_at_approx": "2025-09-21T02:54:31Z",
"published_at_precision": "year",
"edited": false,
"reply_level": 0,
"parent_id": null,
"is_pinned": true,
"pinned_by": "Pinned by @RickAstleyYT",
"creator_hearted": true,
"sort": "top",
"data_source": "innertube.entity"
}
like_count is a magnitude and like_count_text is what the site actually showed. published_at_approx is the latest moment the comment could have been written, because "1 year ago" means anywhere from one to two years. published_at_precision tells you that this date is only good to the year.
Using the results
This script runs the scraper for one video, then prints the run status, the five most-liked threads and how much the channel interacted with its audience. It reads the JSON as a list of rows and accepts exit code 6, since a partial run still writes its rows.
python
import json
import subprocess
import sys
from pathlib import Path
def comment_report(video: str, pages: int = 2) -> None:
out = Path("report_comments")
result = subprocess.run(
[sys.executable, "youtube_scraper.py", "--url", video,
"--pages", str(pages), "--replies", "--format", "json", "--out", str(out)],
capture_output=True, text=True,
)
if result.returncode not in (0, 6):
print(f"Run failed with exit code {result.returncode}\n{result.stderr[-500:]}")
return
rows = json.loads(out.with_suffix(".json").read_text(encoding="utf-8"))
meta = json.loads(Path(f"{out}.meta.json").read_text(encoding="utf-8"))
print(f"Status: {meta.get('status')}, rows: {len(rows)}")
threads = [r for r in rows if r["reply_level"] == 0]
replies = [r for r in rows if r["reply_level"] > 0]
print(f"{len(threads)} threads, {len(replies)} replies")
for r in sorted(threads, key=lambda r: r["like_count"] or 0, reverse=True)[:5]:
flags = " pinned" * bool(r["is_pinned"]) + " hearted" * bool(r["creator_hearted"])
print(f"{r['like_count_text'] or '0':>6} likes, {r['reply_count'] or 0} replies, "
f"{r['published_time_text']}{flags}")
hearted = sum(1 for r in threads if r["creator_hearted"])
print(f"Creator hearted {hearted} of {len(threads)} threads")
if __name__ == "__main__":
comment_report("dQw4w9WgXcQ")
The report deliberately uses like_count_text and published_time_text for display, since those are what YouTube actually published. For sorting, the numeric like_count is good enough as a magnitude.
Limitations
Comment likes are rounded and comment dates are relative. If you need exact numbers or real timestamps, use the official API.
A comments run is always sequential. To go faster, run several videos in parallel as separate processes, or use video mode with --concurrency.
The Scraper API path can't read comments, only video metadata.
pyppeteer is effectively unmaintained and is there for parity. Selenium can't use a password-protected proxy or a Browser API endpoint.
The captcha code has never had a real challenge to solve on YouTube, so treat it as untested readiness.
Common questions
Is it legal to scrape YouTube comments?
The scraper reads publicly visible pages and doesn't get around any login. Comments are written by real people, though, so think about what you collect and store, read YouTube's Terms of Service and follow the law where you are. This isn't legal advice.
Do I need a proxy or a captcha key?
Not for normal use. 1,200 comments came through from a datacentre address with nothing configured. Proxies and the Browser API are for volume, a specific country, or running a browser somewhere else.
Why can't I get exact comment likes or dates?
YouTube doesn't publish them to the web client. Only the official API has them.
Why doesn't --concurrency speed up comments?
Each page of comments is unlocked by a token from the previous page, so they have to be fetched one after another. Parallelism works across videos, not within one.
Why do I get 0 comments with Scraper API?
Because YouTube loads comments with a separate request after the page renders, and a page-rendering service doesn't make that request. Use youtube_scraper.py for comments.
Wrapping up
On YouTube the data is easy to reach, and the work is in reading it honestly. Remember that top and newest are two different samples, and that comment likes and dates are rounded on purpose. If you need exact numbers and a million comments a day, the official API is the better tool; for everything else, the default auto transport needs no setup at all.
Getting started: clone the repository and run it with no setup at all. For volume, a specific country or a hosted browser, sign up for 2Captcha and add residential proxies or the 2Captcha Browser API.
Source code
- Repository: github.com/2scraper/youtube-scraper (MIT)
- Project page: 2scraper.com/scrapers/youtube-scraper
- All scrapers: github.com/2scraper
Documentation
- Quick start: API key, first request, first result.
- Browser API docs: CDP endpoint and profile options.
- Proxy API: generating residential proxy lists.
- Scraper API: fetching pages without a browser.
- Error codes and request limits.
Related guides
- How to run the 2scraper open-source scrapers: setup, exit codes and access modes for every repository.
- How to scrape Google Play: app ratings by country and full review histories.
- How to scrape Catawiki: auction lots, bids and estimates, and why headless fails.
- How to scrape Rakuten: Japanese marketplace prices and points.
- How to scrape Flippa: online businesses for sale, asking prices and profit multiples.