You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过编程获取YouTube视频的播放量、点赞数与评论数

Got it, let's sort this out for you—you’re trying to pull view counts, like counts, and comment counts from a YouTube video URL, but all the search results you’re finding are about uploading videos programmatically. Frustrating, right? Here are the two main ways to get the data you need:

1. Official & Reliable: YouTube Data API v3

This is the go-to method because it’s supported by Google, stable, and doesn’t risk getting your IP blocked. Here’s how to set it up:

  • Step 1: Get an API Key
    Head to the Google Cloud Console, create a new project, enable the YouTube Data API v3 for that project, and generate an API key. It’s free for small-scale use (you get 10,000 API units per day, and each request for video stats uses just 1 unit).

  • Step 2: Extract the Video ID from the URL
    Every YouTube video has a unique 11-character ID. For example:

    • In https://www.youtube.com/watch?v=abc123XYZ, the ID is abc123XYZ
    • In https://youtu.be/abc123XYZ, the ID is also abc123XYZ
      You can extract it with a simple regex (like r'(?:v=|\/)([0-9A-Za-z_-]{11}).*' in Python) or basic string splitting.
  • Step 3: Call the API to Fetch Stats
    Use the videos.list endpoint with the part=statistics parameter. Here’s a Python example to make this easy:

    import requests
    
    def fetch_youtube_video_stats(video_id, api_key):
        api_url = f"https://www.googleapis.com/youtube/v3/videos?part=statistics&id={video_id}&key={api_key}"
        response = requests.get(api_url)
        data = response.json()
        
        if not data.get('items'):
            return None
        
        stats = data['items'][0]['statistics']
        return {
            'view_count': stats.get('viewCount'),
            'like_count': stats.get('likeCount'),
            'comment_count': stats.get('commentCount')
        }
    
    # Replace these with your values
    my_video_id = "abc123XYZ"
    my_api_key = "YOUR_GOOGLE_API_KEY"
    video_stats = fetch_youtube_video_stats(my_video_id, my_api_key)
    print(video_stats)
    

    The response will give you clean, structured numbers for each metric you need. Just make sure to keep your API key secure (don’t hardcode it in frontend code!).

2. Unofficial: Web Scraping (For Small/One-Off Use)

If you don’t want to deal with API keys, you can scrape the video’s web page—but fair warning: YouTube changes its page structure often, so this might break without notice, and excessive scraping could get your IP blocked. Here’s a quick Python example using BeautifulSoup:

import requests
from bs4 import BeautifulSoup
import json

def scrape_youtube_stats(video_url):
    # Mimic a browser request to avoid being blocked
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
    }
    response = requests.get(video_url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Find the hidden script tag with all video data
    data_script = soup.find('script', id='ytInitialData')
    if not data_script:
        return None
    
    video_data = json.loads(data_script.string)
    
    # Extract view count
    view_label = video_data['contents']['twoColumnWatchNextResults']['results']['results']['contents'][0]['videoPrimaryInfoRenderer']['videoActions']['menuRenderer']['topLevelButtons'][0]['toggleButtonRenderer']['defaultText']['accessibility']['accessibilityData']['label']
    view_count = ''.join(filter(str.isdigit, view_label.split(' ')[0]))
    
    # Extract like count
    like_label = video_data['contents']['twoColumnWatchNextResults']['results']['results']['contents'][0]['videoPrimaryInfoRenderer']['videoActions']['menuRenderer']['topLevelButtons'][1]['toggleButtonRenderer']['defaultText']['accessibility']['accessibilityData']['label']
    like_count = ''.join(filter(str.isdigit, like_label.split(' ')[0]))
    
    # Extract comment count
    comment_label = video_data['contents']['twoColumnWatchNextResults']['results']['results']['contents'][1]['videoSecondaryInfoRenderer']['videoInfo']['runs'][1]['text']
    comment_count = ''.join(filter(str.isdigit, comment_label))
    
    return {
        'view_count': view_count,
        'like_count': like_count,
        'comment_count': comment_count
    }

# Usage example
my_video_url = "https://www.youtube.com/watch?v=abc123XYZ"
scraped_stats = scrape_youtube_stats(my_video_url)
print(scraped_stats)

Again, this is a fragile solution—stick with the API if you need something that works long-term.


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

火山引擎 最新活动