YouTube API:无法获取给定通道的所有视频

2024-05-21 04:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试获取给定频道ID的所有视频。但我没有得到所有视频

代码我试图检索频道的所有视频:

api_key =  API_KEY
base_video_url  =  'https://www.youtube.com/watch?v='
base_search_url  =  'https://www.googleapis.com/youtube/v3/search?'
raw_url = 'https://www.googleapis.com/youtube/v3/' \
    'channels?key={}&forUsername={}&part=id'

def getChannelID(username):
    ''' returns the channel ID '''
    r=requests.get(raw_url.format(api_key,username))
    json=r.json()
    print(json['items'][0]['id'])
    return json['items'][0]['id']

def getchannelVideos():
   ''' returns list of all videos of a given channel '''
   chanId=getChannelID('tseries')
   first_url = base_search_url + \
          'order=date&part=snippet&channelId={}&maxResults=50&key={}'\
                        .format(chanId,api_key)

   video_links = []
   url = first_url
   while True:
      inp = requests.get(url)
      resp = inp.json()

      for i in resp['items']:
          if i['id']['kind'] == "youtube#video":
              video_links.append(base_video_url + i['id']['videoId'])

      try:
          next_page_token = resp['nextPageToken']
          url = first_url + '&pageToken={}'.format(next_page_token)
      except:
          break
      print('working') #used this to count repetitions of while loop
   return video_links

这里给定的频道是T-Series,到目前为止已经有11537个视频 [click to see the image of the channel showing the count ]但我只收到了589个视频

我用这一行来计算循环的迭代次数

^{pr2}$

为此,我观察到while循环在19次迭代后结束(我尝试过许多通道,但同样是重复的)

Json(Json)提供的最后一次数据是I

{'etag': "cbz3lIQ2N25AfwNr-BdxUVxJ_QY/7SEM6nSU4tBD7ZsR5Abt5L-uqAE",
 'items': [],
 'kind': 'youtube#searchListResponse',
 'pageInfo': {'resultsPerPage': 50, 'totalResults': 15008},
 'prevPageToken': 'CLYHEAE',
 'regionCode': 'IN'}

为什么API不提供nextpageID,虽然totalResults是15008??在


Tags: ofthekeyhttpsapiidjsonurl
2条回答

正如已经在评论中提到的,从结果中可以检索到的最多视频是50个。因此,如果您想访问其他51-100等等,您必须使用nextPageToken

pageToken

The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.

检查这个Python on App Engine Code Samples以获取使用Python进行Youtube API调用的示例。在

搜索调用不用于枚举通道。在

在最近找到这个之前,我一直在用HTML抓取channel>;videos页面。在

https://stackoverflow.com/a/27872244/975887

基本上步骤是

  • 找到所需频道的频道ID。在
  • 列出播放列表(youtube.channels.listid设置为channelId,并将部分设置为contentDetails
  • 查找名为uploads的播放列表的ID
  • 列出播放列表项(youtube.playlistItems.list设置playlistId并将part设置为snippet,可选地将maxResults设置为50)
  • 使用nextPageToken翻页浏览结果

If you only know a video ID, you can call youtube.videos.list with id set to video id and part set to snippet and extract the channel ID from the result.

这个列表列出了频道上传的所有视频,与搜索调用不同的是,在100个项目之后不会放弃,并且结果总是来自指定的频道。在

{1}每一个呼叫加上一个额外的搜索点数,这取决于每一次呼叫的费用。在

相关问题 更多 >