如何使用 Youtube API 从 Youtube 中提取评论 - Python

2025年1月11日 | 阅读 4 分钟

YouTube 是世界上最受欢迎的视频分享网站,每天有数百万用户在各种视频上发布评论。对于不同的研究或分析应用,从这些评论中提取信息可能是一个重要的资源。使用 Python 编程,可以通过 YouTube API 轻松检索评论。在本教程中,我们将介绍如何使用 Python 的 YouTube API 来检索 YouTube 评论。

第一步:在 Google Developers Console 中创建项目

要使用 YouTube API,您需要在 Google Developers Console 中创建一个项目。访问 https://console.developers.google.com/ 并创建一个新项目。项目建立后,您可以转到 API 和服务信息中心,使用搜索字段搜索“YouTube Data API v3”来启用 YouTube Data API v3。点击它以激活项目中的 API。

第二步:安装所需的库

要提取 YouTube 评论,您需要安装以下库

  1. google-auth
  2. google-auth-oauthlib
  3. google-auth-httplib2
  4. google-api-python-client

您可以使用 pip 包管理器通过在终端中运行以下命令来安装这些库

代码

第三步:获取授权凭据

要访问 YouTube API,您需要获取授权凭据。请按照以下步骤获取凭据

  • 转到 Google Developers Console。
  • 选择您的项目。
  • 导航到 API 和服务信息中心,然后从左侧菜单中选择“凭据”。
  • 点击“创建凭据”,然后选择“OAuth 客户端 ID”。
  • 选择“桌面应用”作为应用程序类型。
  • 为您的客户端 ID 命名,然后点击“创建”。
  • 下载 client_secret.json 文件并将其保存到您的本地计算机。

第四步:提取 YouTube 评论

现在您已完成初始设置,可以使用以下 Python 代码提取 YouTube 评论

代码

输出

Number of comments: 10
Comment 1 : This is an awesome video!
Comment 2 : I learned a lot from this video. Thanks for this video!
Comment 3 : Great tutorial! Clear and concise, recommended for Learners.
Comment 4 : This is so helpful, thank you so much for posting!
Comment 5 : You make it look so easy! Thanks for sharing.
Comment 6 : Amazing content, keep it up mate!
Comment 7 : Thank you for explaining this so well. Excellent Tutorial!
Comment 8 : I love your videos very much, they're always so informative.
Comment 9 : Thanks for taking the time to create this tutorial.
Comment 10 : This is exactly what I was looking for so long time. Thanks for sharing!

上述评论仅供示例使用,并且会根据代码中提供的视频 ID 而有所不同。此外,根据视频及其评论数量,评论数量也可能有所不同。

结论

总而言之,使用 Python 和 YouTube API 检索 YouTube 评论是一个简单的过程。YouTube API 为开发人员提供了一个简单的接口,用于从特定的 YouTube 视频中提取评论。借助 Python 库 google-auth 和 googleapiclient,我们可以登录 YouTube API 并检索视频的评论。总的来说,使用 Python 和 YouTube API 收集 YouTube 评论是研究用户行为、评估用户情绪和创建更好产品的有用工具。