Skip to main content
 首页 » 编程设计

python之如何获取视频、youtubeAPI、Python 的 channel 名称

2025年05月04日7freeliver54

首先,之前对类似问题的“回答”使用了已弃用的 Youtube Api V2。此外,没有一个答案显示了如何使用 Python 来完成。

我的代码是:

def youtube_search(item): 
 
 
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, 
    developerKey=DEVELOPER_KEY) 
 
  # Call the search.list method to retrieve results matching the specified 
  # query term. 
  search_response = youtube.search().list( 
    q=item, 
    part="id,snippet", 
    maxResults=6 
  ).execute() 
 
 
  videoCount = 0; 
  title = "" 
  channelId = "" 
  channelName = "" 
  # Add each result to the appropriate list, and then display the lists of 
  # matching videos, channels, and playlists. 
  for search_result in search_response.get("items", []): 
    if search_result["id"]["kind"] == "youtube#video": 
      videoCount += 1 
      if videoCount == 1: 
         snippet = search_result["snippet"] 
         title = snippet["title"] 
         channelId = snippet["channelId"] 
         channelName = snippet["channelTitle"]  
 
#  print "Videos:\n", "\n".join(videos), "\n" 
  print( item, videoCount, title, channelId, channelName ) 

所以基本上从第一个返回的视频我想知道视频的标题和 channel 的名称。这是我特别要找的名字。对于这个搜索字符串:

r'''"Joe Keegan" "Pick Myself Up"''' 

我的结果是:

('"Joe Keegan" "Pick Myself Up"', 1, u'Pick Myself Up', u'UCThUpINg-JADDOHdkz_4-jw', u'') 

我在这里找的 channel 名称是“群星-话题”。特别是我有一个巨大的列表,并试图消除任何具有该 channel 名称的列表(很多)。然而,有很多 channel ID 使用该名称。 channelTitle 没有给我我要找的东西。

请您参考如下方法:

虽然这一切都在进行,但我一直在尝试自己解决它,并合并了周围的其他一些答案,以提出一个可行的解决方案。它可能不是最好的,所以如果您有更好的请告诉我。但它可能对其他偶然尝试做同样事情的人有用:

基本上,我对视频 ID 执行了 URL“获取”请求并解析了 JSON 响应。哦,Python 有时是一种非常容易使用的语言......

  for search_result in search_response.get("items", []): 
    if search_result["id"]["kind"] == "youtube#video": 
      videoCount += 1 
      if videoCount == 1: 
         snippet = search_result["snippet"] 
         title = snippet["title"] 
         videoId = search_result["id"]["videoId"]  
         channelId = snippet["channelId"] 
 
  urlBase = "https://gdata.youtube.com/feeds/api/videos/" 
  if videoCount > 0: 
     url = urlBase + videoId + "?v=2&alt=json" 
     r = requests.get(url) 
     metadata = r.json() 
     channelName = metadata["entry"]["author"][0]["name"]["$t"] 
 
print( item, videoCount, title, channelId, channelName ) 

当然我真的不需要 channelId...