Python调用YouTube API按地区筛选视频时非英语视频问题及region_code报错求助
Hey there! Let's work through your two issues step by step—they're both fixable with a few tweaks to your code and a better grasp of how the YouTube API works.
1. Fixing the 'US' is undefined error
This error happens because Python interprets US as a variable name instead of a string value. You just need to make sure you pass the region code as a quoted string when calling your search_video function.
- If you're hardcoding the region:
# Correct: wrap 'US' in single or double quotes videoids = search_video("your_target_keyword", "US", comments) - If you're getting the region from user input:
# Input returns a string by default, no extra quotes needed region_code = input("Enter region code (e.g., US): ") videoids = search_video("your_target_keyword", region_code, comments)
2. Fixing unexpected video languages & broken category logic
Your current code has two key issues causing mismatched results:
A. Your category ID function isn't working as intended
Right now, get_category_id just returns the first category ID it finds in the region—completely ignoring the cat (keyword) parameter you pass. That means you're likely searching videos from a random category, not the one you want.
Here's a fixed version that actually matches the category name you specify:
def get_category_id(youtube, category_name, region_code): req = youtube.videoCategories().list(part='snippet', regionCode=region_code) response = req.execute() # Match category name (case-insensitive to avoid typos) for item in response["items"]: if item["snippet"]["title"].lower() == category_name.lower(): return item["id"] # Return None if no matching category is found return None
Update your search function to pass the region code to this helper, and make sure you're passing a valid category name (like "Music" or "Gaming") as the keyword argument to search_video.
B. Region code doesn't filter video language
The region_code parameter prioritizes content popular in that region, but it doesn't force videos to be in the region's primary language. To filter for English videos specifically, add the relevanceLanguage='en' parameter to your search request, plus include regionCode=region_code to tie results to the US region:
req = youtube.search().list( videoCategoryId=video_category_id, order='date', maxResults=len(comments), publishedAfter=(datetime.datetime.utcnow() + datetime.timedelta(minutes = -1)).isoformat('T')+'Z', part='snippet', type='video', # Add these two lines to lock in region and language regionCode=region_code, relevanceLanguage='en' )
Quick Final Checks
- Ensure you're passing a valid category name (not a video keyword) to
search_video(e.g., use "Gaming" if you want gaming videos) - If you still see occasional non-English videos, you can add an extra check to filter results by the
snippet.languagefield in the API response, butrelevanceLanguageshould handle most cases.
内容的提问来源于stack exchange,提问作者JaxxGoyu

