You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python获取YouTube热门视频数据:CSV保存失败及报错求助

Hey there! Let’s tackle your problem step by step—first fixing that NameError, then getting your data saved to a CSV file.

1. Resolve the NameError: name 'response' is not defined

That error is telling you your code doesn’t recognize the response variable because you never created it by capturing the API’s output. When using the YouTube Data API with the google-api-python-client library, you need to explicitly assign the result of your API request to response. Here’s how that should look:

from googleapiclient.discovery import build
import csv

# Replace with your actual API key
API_KEY = "YOUR_YOUTUBE_API_KEY"

# Initialize the YouTube API client
youtube = build('youtube', 'v3', developerKey=API_KEY)

# Make the API request AND assign the response to a variable
request = youtube.videos().list(
    part="snippet,statistics",  # Include the data categories you need
    chart="mostPopular",
    regionCode="US",  # Adjust to your target region
    maxResults=50
)
response = request.execute()  # This line creates the 'response' variable you were missing!

Also, your line Data = json.loads(str(response,'utf-8')) is unnecessary—request.execute() already returns a Python dictionary, so you can work directly with response without converting it again.

2. Save the Data to CSV

Now that you have a valid response object, let’s extract key fields and write them to a CSV using Python’s built-in csv module:

# Define the columns you want in your CSV file
csv_columns = [
    "video_id",
    "title",
    "published_date",
    "view_count",
    "like_count",
    "channel_title"
]

# Open a CSV file for writing (use 'w' to create/overwrite, 'a' to append)
with open('youtube_trending_videos.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=csv_columns)
    writer.writeheader()  # Write column headers first

    # Loop through each video entry in the API response
    for video in response['items']:
        # Extract data from the response dictionary
        video_row = {
            "video_id": video["id"],
            "title": video["snippet"]["title"],
            "published_date": video["snippet"]["publishedAt"],
            "view_count": video["statistics"].get("viewCount", "N/A"),  # Use get() to avoid missing field errors
            "like_count": video["statistics"].get("likeCount", "N/A"),
            "channel_title": video["snippet"]["channelTitle"]
        }
        writer.writerow(video_row)

Key Tips:

  • Using .get() for statistics fields (like viewCount) prevents KeyError if a video doesn’t have that data (some restricted or old videos might omit stats).
  • Setting encoding='utf-8' ensures non-English characters in titles or channel names display correctly in the CSV.
  • Double-check that your part parameter in the API request includes all the data categories you’re trying to extract (e.g., snippet for titles, statistics for view counts).

Final Quick Checks

  • Make sure you’ve installed the required library: pip install google-api-python-client
  • Verify your API key is valid and has access to the YouTube Data API v3.

内容的提问来源于stack exchange,提问作者Nilam Adhikari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:24:09