如何根据唯一频道名称或ID返回YouTube频道信息

Dom*_*nik 5 python youtube-data-api

@username我正在尝试编写一个简单的 Python 脚本,通过或搜索返回有关频道的一些信息UCrandomID123

我知道您可以使用以下端点来访问频道数据:https://www.googleapis.com/youtube/v3/channels

然而,我遇到了一些可能的限制和问题。某些频道的频道 URL 中可能没有自定义“名称”:

在此输入图像描述

在此输入图像描述

我查了一下问题并发现了多个解决该问题的帖子:

但这两种解决方案都相当陈旧,我想知道现在是否有更好的解决方案来解决这个问题?

我有以下代码:

async def get_channel_id(self, channel_input):
        api_url = f"https://www.googleapis.com/youtube/v3/channels"
        params = {
            'part': 'snippet',
            'key': DEVELOPER_KEY,
            'maxResults': 1
        }

        # Determine if the input is a channel ID or username
        if channel_input.startswith('UC'):
            # Channel ID provided
            params['id'] = channel_input
        else:
            # Assume it's a custom username
            params['forUsername'] = channel_input

        response = await self.make_api_request(api_url, params) # Just a function to make an async req.
        if response and response.get('items'):
            channel_info = response['items'][0]
            channel_id = channel_info['id']
            channel_title = channel_info['snippet']['title']
            channel_url = f"https://www.youtube.com/channel/{channel_id}"
            return channel_id, channel_title, channel_url
        return None, None, None
Run Code Online (Sandbox Code Playgroud)

如果我有 URL UC....,但给出唯一的“用户名”,则此方法工作正常,由于某种原因它无法找到该频道。我想要捕获这两种情况的原因是,目前大多数频道都有这样的自定义名称 URL。

小智 0

我开发了一个修改查询参数的解决方案

希望这对你有用

import requests

# Replace with your own Google API key
DEVELOPER_KEY = 'your_api_key_here'

def get_channel_id(channel_input):
    api_url = "https://www.googleapis.com/youtube/v3/search"
    params = {
        'part': 'snippet',
        'key': DEVELOPER_KEY
    }

    # Determine if the input is a channel ID or username
    if channel_input.startswith('@'):
        # Username provided
        params['type'] = 'channel'
        params['q'] = channel_input
    elif channel_input.startswith('UC'):
        # Channel ID provided
        params['id'] = channel_input
        params['maxResults'] = 1
    else:
        print("Invalid input format. Please provide a valid YouTube username (starting with '@') or channel ID (starting with 'UC').")
        return None, None, None

    response = requests.get(api_url, params=params)

    if response.status_code == 200:
        data = response.json()
        if 'items' in data and data['items']:
            channel_info = data['items'][0]['snippet']
            channel_id = channel_info['channelId']
            channel_title = channel_info['title']
            channel_url = f"https://www.youtube.com/channel/{channel_id}"
            return channel_id, channel_title, channel_url
        else:
            print("No channels found in the response.")
    else:
        print(f"Error: {response.status_code}")
        print(response.text)

    return None, None, None

# Replace 'your_channel_input_here' with the YouTube username or channel ID you want to search for
channel_input_to_search = 'UC or @Username'

# Run the search
result = get_channel_id(channel_input_to_search)
print(result)
Run Code Online (Sandbox Code Playgroud)