youtube-transcript-api 為何在本機正常、部署到伺服器後失敗?3 種修復方法
youtube-transcript-api works on my laptop but fails on my server: why, and 3 fixes
youtube-transcript-api 在雲端伺服器上出現 RequestBlocked、IpBlocked 或「could not retrieve a transcript」時,常見原因是 YouTube 封鎖雲端供應商的 IP 範圍,而非程式碼本身出錯。
You wrote ten lines of Python with youtube-transcript-api, tested it locally, and it worked. You deployed it to AWS, GCP, Azure, DigitalOcean, Render or a Docker container on a VPS, and now every call fails with RequestBlocked, IpBlocked, or a vague "could not retrieve a transcript" error.
This is one of the most common questions about YouTube transcripts right now. It shows up on Stack Overflow, in the library's own issue tracker, and in the n8n forum. Your code is almost certainly fine. Here is what is going on and what you can do.
Why it happens
YouTube treats traffic from cloud provider IP ranges very differently from traffic from a home connection. The library's README says it plainly: YouTube has started blocking most IPs known to belong to cloud providers, so RequestBlocked and IpBlocked are expected when you deploy.
A few details that trip people up:
- It is the IP range, not your request volume. A brand new server can be blocked on its very first request.
- Free proxy tiers usually do not help. Datacenter proxies are cloud IPs too. One user in issue #593 found that a free proxy plan only gave datacenter IPs, which YouTube also blocked.
- "No transcript" is not always true. When you are blocked, some code paths surface it as a missing transcript. Before you tell a user a video has no captions, check that you are not blocked.
Step 1: confirm it is a block
First make sure you are on the current API (version 1.x). Older tutorials use YouTubeTranscriptApi.get_transcript() and list_transcripts(), which were replaced by instance methods.
from youtube_transcript_api import (
YouTubeTranscriptApi,
RequestBlocked,
IpBlocked,
TranscriptsDisabled,
NoTranscriptFound,
)
ytt = YouTubeTranscriptApi()
def get_text(video_id: str) -> str | None:
try:
fetched = ytt.fetch(video_id, languages=["en"])
return " ".join(s.text for s in fetched)
except (RequestBlocked, IpBlocked):
# This is the server problem. The video may well have captions.
raise
except (TranscriptsDisabled, NoTranscriptFound):
return None # genuinely no usable transcript
print(get_text("aircAruvnKk"))
Run the same script locally and on the server. If it works locally and raises RequestBlocked or IpBlocked on the server, you have your answer.
Fix 1: route requests through residential proxies
This is the fix the library maintainer recommends, and the library has built in support for it:
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.proxies import WebshareProxyConfig
ytt = YouTubeTranscriptApi(
proxy_config=WebshareProxyConfig(
proxy_username="YOUR_USERNAME",
proxy_password="YOUR_PASSWORD",
filter_ip_locations=["us"], # optional, helps with region locked videos
)
)
Any other provider works through GenericProxyConfig:
from youtube_transcript_api.proxies import GenericProxyConfig
ytt = YouTubeTranscriptApi(
proxy_config=GenericProxyConfig(
http_url="http://user:pass@proxy.example.com:8000",
https_url="http://user:pass@proxy.example.com:8000",
)
)
What to know:
- It has to be residential (or mobile). Datacenter proxies are usually blocked for the same reason your server is.
- Use rotating IPs and retry on
RequestBlockedwith a fresh IP. - If some videos fail only through the proxy with "not available in your country", pin the proxy country with
filter_ip_locations(issue #618 is exactly this case). - Cost: you pay per GB of proxy traffic. Transcripts are small, so it is usually cheap, but you now own the proxy account, the retries and the monitoring.
Fix 2: fetch from a machine that is not in a cloud range
If your volume is small, move only the transcript fetching off the cloud:
- Run a small worker on a home machine or office server that fetches transcripts and pushes them to your database or a queue.
- Your cloud app reads from that store instead of calling YouTube directly.
This is free and works well for a personal project. It is fragile for anything customer facing, because your app now depends on a box under someone's desk staying online, and a residential IP can still get rate limited if you push hundreds of videos an hour.
Fix 3: use a hosted transcript service
The third option is to let someone else run the proxy and retry layer. There are several hosted transcript APIs (the library's README links to one), and there are transcript scrapers on the Apify Store.
I build one of those, the YouTube Transcript Scraper, so here is how it looks from code, for completeness:
from apify_client import ApifyClient
client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("zhtech/youtube-transcript-scraper").call(run_input={
"urls": [
"https://www.youtube.com/watch?v=aircAruvnKk",
"https://www.youtube.com/@3blue1brown", # a whole channel works too
],
"maxVideosPerSource": 20,
"languages": ["en"],
"outputFormats": ["text", "segments"],
})
for row in client.dataset(run["defaultDatasetId"]).iterate_items():
if row.get("status") == "success":
print(row["videoId"], row["wordCount"], row["text"][:80])
else:
print(row["videoId"], "no transcript:", row.get("errorCode"))
It escalates from datacenter to residential IPs only for the requests YouTube blocks, and it double checks "no captions" from a second IP before reporting it. Videos without a transcript come back as free rows with an error code, and you pay per delivered transcript (about $1 per 1,000 on the free plan at the time of writing).
Which one should you pick?
| Situation | My pick |
|---|---|
| Hobby project, a few videos a day | Fix 2 (local worker) or just run it locally |
| You already pay for residential proxies | Fix 1 |
| Production app, you do not want to maintain proxy logic | Fix 3, any hosted service |
| Whole channels or playlists on a schedule | Fix 3, or Fix 1 plus your own channel listing code |
The main thing is to stop treating RequestBlocked as a bug in your code. It is a network problem, and the fix is about where your requests come from.
Disclosure: I build the YouTube Transcript Scraper mentioned in Fix 3. Published by ZH Tech. This post was written with AI assistance and reviewed before publishing.
來源:DEV Community · dev.to