Python中如何爬取YouTube视频评论?

想爬取油管的评论,有没有现成的工具?


Python中如何爬取YouTube视频评论?
15 回复

没有 api 吗


import requests
import json
from typing import List, Dict

class YouTubeCommentsScraper:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://www.googleapis.com/youtube/v3"
        
    def get_video_comments(self, video_id: str, max_results: int = 100) -> List[Dict]:
        """获取视频评论"""
        comments = []
        url = f"{self.base_url}/commentThreads"
        params = {
            'part': 'snippet',
            'videoId': video_id,
            'key': self.api_key,
            'maxResults': min(max_results, 100),  # API单次最多100条
            'order': 'relevance'
        }
        
        try:
            while len(comments) < max_results:
                response = requests.get(url, params=params)
                response.raise_for_status()
                data = response.json()
                
                for item in data.get('items', []):
                    comment = item['snippet']['topLevelComment']['snippet']
                    comments.append({
                        'author': comment['authorDisplayName'],
                        'text': comment['textDisplay'],
                        'likes': comment['likeCount'],
                        'published_at': comment['publishedAt']
                    })
                    
                    if len(comments) >= max_results:
                        break
                
                # 检查是否有下一页
                next_page_token = data.get('nextPageToken')
                if not next_page_token or len(comments) >= max_results:
                    break
                    
                params['pageToken'] = next_page_token
                
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
        except KeyError as e:
            print(f"数据解析错误: {e}")
            
        return comments[:max_results]

# 使用示例
if __name__ == "__main__":
    # 需要先在Google Cloud Console创建项目并启用YouTube Data API v3
    API_KEY = "你的API密钥"
    VIDEO_ID = "dQw4w9WgXcQ"  # 替换为目标视频ID
    
    scraper = YouTubeCommentsScraper(API_KEY)
    comments = scraper.get_video_comments(VIDEO_ID, max_results=50)
    
    # 保存到JSON文件
    with open('youtube_comments.json', 'w', encoding='utf-8') as f:
        json.dump(comments, f, ensure_ascii=False, indent=2)
    
    print(f"成功爬取 {len(comments)} 条评论")
    for i, comment in enumerate(comments[:3], 1):
        print(f"\n评论{i}:")
        print(f"作者: {comment['author']}")
        print(f"内容: {comment['text'][:100]}...")

核心要点:

  1. 必须使用YouTube Data API v3,直接爬取HTML违反服务条款
  2. 需要Google Cloud项目并启用API,获取API密钥
  3. 免费版每天有配额限制(约10,000次请求/天)
  4. 评论数据包含作者、内容、点赞数、时间等字段

重要提醒:

  • 遵守YouTube API服务条款和配额限制
  • 处理分页使用nextPageToken参数
  • 注意API版本和参数的正确性
  • 考虑添加错误处理和重试机制

替代方案: 如果需要大量爬取,可以考虑:

  • 使用youtube-comment-downloader第三方库
  • 通过Selenium模拟浏览器(但可能违反条款)

一句话建议: 用官方API最稳妥,注意配额和条款。

不懂哈,第一次弄这个

这个很简单,抓包下就能看到请求链接了。

YouTube 有 api 的

就算搞定采集程序, 没采集几页就遭遇 reCAPTCHA 了, 挂代理池大部分撞 reCAPTCHA…

那如何实现大量采集呢

大量采集,基本不可能,装 reCAPTCHA 还算好的,如果给你返回假数据更难搞。

感觉很多评论信息量很大啊

比如说?采集评论有啥用

妈耶,这个评论图片还需要打开才能看

妈耶,这个图片分明是 #8 的头像……大概是 把图片拖进评论框了……

selenium

感谢。

回到顶部