如何通过YouTube API获取播放列表视频时长?避免单视频请求的方法
YouTube播放列表批量获取视频时长的高效方案
YouTube确实已经移除了playlistItems().list()接口返回视频时长的功能,现在该接口的contentDetails字段仅提供videoId和videoPublishedAt。目前没有无需额外请求就能获取时长的方法,但可以通过批量调用videos().list()接口大幅降低请求次数,提升效率——该接口支持一次传入最多50个videoId,不用逐个请求单条视频。
优化后的代码示例
你可以修改原有代码,先收集播放列表中所有视频的videoId,再分批批量查询时长,最后将时长数据合并到原播放列表数据中:
from googleapiclient.discovery import build API_KEY = "你的API密钥" youtube = build("youtube", "v3", developerKey=API_KEY) def get_playlist_videos_with_duration(playlist_id): collected_data = [] next_page_token = None # 第一步:获取播放列表所有视频的基本信息和videoId while True: request = youtube.playlistItems().list( part='snippet,contentDetails', playlistId=playlist_id, maxResults=50, pageToken=next_page_token ) response = request.execute() collected_data.extend(response['items']) next_page_token = response.get('nextPageToken') if not next_page_token: break # 第二步:收集所有videoId,分批批量查询时长 video_ids = [item['contentDetails']['videoId'] for item in collected_data] video_durations = {} # 按50个id一组拆分 for i in range(0, len(video_ids), 50): batch_ids = video_ids[i:i+50] request = youtube.videos().list( part='contentDetails', id=','.join(batch_ids) ) response = request.execute() # 存储videoId和对应的时长(ISO 8601格式,比如PT1M30S) for video in response['items']: video_durations[video['id']] = video['contentDetails']['duration'] # 第三步:将时长合并到原数据中 for item in collected_data: video_id = item['contentDetails']['videoId'] item['contentDetails']['duration'] = video_durations.get(video_id) return collected_data
关键说明
- 批量查询:
videos().list()的id参数支持用逗号分隔多个videoId,一次最多传50个,这样即使播放列表有1000个视频,也只需要20次请求,而非1000次。 - 数据合并:通过
videoId作为关联键,把查询到的时长字段追加到原播放列表条目中,方便后续使用。 - 时长格式:返回的时长是ISO 8601格式(如
PT1H2M3S表示1小时2分3秒),如果需要转成秒数,可以用isodate库或者自定义函数解析。
内容的提问来源于stack exchange,提问作者Obektev
相关产品推荐
相关产品推荐

