knowhow.md 6.95 KB

YouTube 热门视频爬虫技术调研报告

1. 方案概述

1.1 推荐方案优先级

方案 推荐指数 稳定性 复杂度 适用场景
YouTube Data API v3 ⭐⭐⭐⭐⭐ 高 低 生产环境首选
yt-dlp ⭐⭐⭐⭐ 中高 低 无需 API Key 的替代方案
页面解析 (Scrapy) ⭐⭐⭐ 中 高 需要绕过 API 限制时
Selenium/Playwright ⭐⭐ 低 高 仅作为兜底方案

1.2 核心字段覆盖

所有方案均需提取以下字段:

  • videoId / url - 视频唯一标识和链接
  • title - 视频标题
  • viewCount - 播放量
  • channelTitle - 频道名称
  • thumbnails - 封面缩略图 URL
  • publishedAt - 发布时间(可选)

2. YouTube Data API v3 (推荐方案)

2.1 API 端点

GET https://www.googleapis.com/youtube/v3/videos

2.2 关键参数

参数 类型 必填 说明
part string 是 snippet,statistics,contentDetails
chart string 是 固定值 mostPopular
regionCode string 否 ISO 3166-1 alpha-2 代码,如 US, CN, JP
videoCategoryId string 否 视频分类 ID,如 10(音乐), 20(游戏)
maxResults integer 否 1-50,默认 5
key string 是 Google API Key

2.3 响应格式

{
  "kind": "youtube#videoListResponse",
  "items": [
    {
      "id": "dQw4w9WgXcQ",
      "snippet": {
        "title": "Video Title",
        "channelTitle": "Channel Name",
        "publishedAt": "2024-01-15T10:00:00Z",
        "thumbnails": {
          "default": {"url": "...", "width": 120, "height": 90},
          "medium": {"url": "...", "width": 320, "height": 180},
          "high": {"url": "...", "width": 480, "height": 360}
        }
      },
      "statistics": {
        "viewCount": "1000000",
        "likeCount": "50000"
      }
    }
  ]
}

2.4 配额说明

  • 每日配额: 10,000 units/天
  • mostPopular 请求: 1 unit/次
  • search 请求: 100 units/次(避免使用)

2.5 常用分类 ID

分类 ID
Film & Animation 1
Autos & Vehicles 2
Music 10
Sports 17
Gaming 20
People & Blogs 22
Comedy 23
Entertainment 24
News & Politics 25
Education 27
Science & Technology 28

3. yt-dlp 方案 (无 API)

3.1 方案特点

  • 优点: 无需 API Key,可直接获取 trending 数据
  • 缺点: 依赖 yt-dlp 库的维护,YouTube 页面结构变化时可能失效
  • 稳定性: 2025 年最新版本 (2025.11.12) 支持良好

3.2 Python 实现

import yt_dlp

def get_trending_yt_dlp(limit=50):
    """使用 yt-dlp 获取 YouTube 热门视频"""
    ydl_opts = {
        'extract_flat': True,
        'playlistend': limit,
        'quiet': True,
        'no_warnings': True,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(
            'https://www.youtube.com/feed/trending',
            download=False
        )

        videos = []
        for entry in info.get('entries', []):
            videos.append({
                'videoId': entry.get('id'),
                'url': f"https://youtube.com/watch?v={entry.get('id')}",
                'title': entry.get('title'),
                'channelTitle': entry.get('uploader'),
                'viewCount': entry.get('view_count'),
                'thumbnail': entry.get('thumbnail'),
                'duration': entry.get('duration'),
            })

        return videos
TRENDING_URLS = {
    'default': 'https://www.youtube.com/feed/trending',
    'music': 'https://www.youtube.com/feed/trending?bp=4gINGgt5dG1hX2NoYXJ0cw%3D%3D',
    'gaming': 'https://www.youtube.com/feed/trending?bp=4gIcGhpnYW1pbmdfY29udGVudF9mZWVk',
    'movies': 'https://www.youtube.com/feed/trending?bp=4gIKGgh0cmFpbGVycw%3D%3D',
}

4. 页面解析方案 (备用)

4.1 技术原理

YouTube trending 页面在 window.ytInitialData JavaScript 变量中嵌入初始数据,可通过正则提取:

import requests
import json
import re

def scrape_trending_page():
    """从 YouTube trending 页面提取数据"""
    url = "https://www.youtube.com/feed/trending"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.0',
    }

    response = requests.get(url, headers=headers)

    # 提取 ytInitialData
    match = re.search(r'var ytInitialData = ({.*?});', response.text)
    if match:
        data = json.loads(match.group(1))
        # 解析 videos...
        return parse_yt_initial_data(data)

    return []

4.2 注意事项

  • YouTube 经常更改 HTML 结构,此方案脆弱
  • 需要处理 Cookie 同意弹窗(欧盟地区)
  • 频繁请求会触发反爬虫机制

5. pytube 说明

重要: pytube 库本身不支持直接获取 trending 视频。它主要用于:

  • 视频下载
  • 视频元数据获取(已知 URL)
  • 关键词搜索

如需使用 pytube,只能先通过其他方式获取视频 URL,再用 pytube 获取详情:

from pytube import YouTube

def enrich_with_pytube(video_id):
    """使用 pytube 补充视频详情"""
    yt = YouTube(f"https://youtube.com/watch?v={video_id}")
    return {
        'title': yt.title,
        'author': yt.author,
        'views': yt.views,
        'length': yt.length,
        'thumbnail_url': yt.thumbnail_url,
    }

6. 反爬虫与限制

6.1 YouTube 防护机制

  • Rate Limiting: 频繁请求会返回 429
  • Bot Detection: 检测 headless Chrome
  • CAPTCHA: 异常流量触发验证码
  • IP 封禁: 严重违规可能封禁 IP

6.2 最佳实践

  1. 优先使用 API: 合法、稳定、有文档
  2. 请求间隔: 使用 yt-dlp 或爬虫时,添加 2-5 秒延迟
  3. User-Agent: 使用真实浏览器 UA
  4. 缓存: Trending 数据 15-30 分钟内不会大幅变化,建议缓存

7. 推荐实现策略

7.1 生产环境

主方案: YouTube Data API v3
备用方案: yt-dlp
监控: API 配额使用率、成功率

7.2 字段映射

目标字段 API 路径 yt-dlp 字段
videoId id id
url https://youtube.com/watch?v={id} webpage_url
title snippet.title title
channelTitle snippet.channelTitle uploader
viewCount statistics.viewCount view_count
thumbnail snippet.thumbnails.high.url thumbnail
publishedAt snippet.publishedAt upload_date

8. 总结

  1. YouTube Data API v3 是最稳定、推荐的方案,适合生产环境
  2. yt-dlp 是优秀的无 API 替代方案,维护活跃
  3. 页面解析 和 Selenium 仅作为兜底方案,维护成本高
  4. pytube 不直接支持 trending 获取,仅用于辅助

建议 Agent 优先实现 API 方案,同时支持 yt-dlp 作为降级方案。