python:获取某个频道的所有youtube视频网址

问题描述:

我想获取特定频道的所有视频网址。我认为使用python或java的json将是一个不错的选择。我可以用下面的代码得到最新的视频,但我怎样才能获得所有视频链接(> 500)?python:获取某个频道的所有youtube视频网址

import urllib, json 
author = 'Youtube_Username' 
inp = urllib.urlopen(r'http://gdata.youtube.com/feeds/api/videos?max-results=1&alt=json&orderby=published&author=' + author) 
resp = json.load(inp) 
inp.close() 
first = resp['feed']['entry'][0] 
print first['title'] # video title 
print first['link'][0]['href'] #url 

增加1最大结果到然而,许多你想要的,但要小心,他们不建议抓住一个电话太多,并会限制你在50(https://developers.google.com/youtube/2.0/developers_guide_protocol_api_query_parameters)。相反,你可以考虑通过改变起始索引直到没有回来的数据来批量抓取25个数据。

编辑:下面是我会怎么做

import urllib, json 
author = 'Youtube_Username' 

foundAll = False 
ind = 1 
videos = [] 
while not foundAll: 
    inp = urllib.urlopen(r'http://gdata.youtube.com/feeds/api/videos?start-index={0}&max-results=50&alt=json&orderby=published&author={1}'.format(ind, author)) 
    try: 
     resp = json.load(inp) 
     inp.close() 
     returnedVideos = resp['feed']['entry'] 
     for video in returnedVideos: 
      videos.append(video) 

     ind += 50 
     print len(videos) 
     if (len(returnedVideos) < 50): 
      foundAll = True 
    except: 
     #catch the case where the number of videos in the channel is a multiple of 50 
     print "error" 
     foundAll = True 

for video in videos: 
    print video['title'] # video title 
    print video['link'][0]['href'] #url 
+1

很好的回答,但它会更好地使用类似“除了SpecificError”,而不是一般异常:如果有其他问题与JSON负载或与响应分析,这种代码会隐藏起来。 – 2013-03-20 08:06:02

+1

好点,如果海报决定使用它,那么绝对是一个好主意做一些研究,并找到具体的错误 – 2013-03-21 00:15:03

+0

如果你将删除:打印len(视频),那么你会得到错误...所以我认为将需要解决该问题。 – 2014-02-08 15:25:38

基于这里找到的代码,并在其他一些地方,我写了一个小脚本,做这个的代码。我的脚本使用Youtube API的v3版本,并且没有针对Google为搜索设置的500个结果限制。

的代码可以在GitHub上:https://github.com/dsebastien/youtubeChannelVideosFinder

+1

感谢您的支持。结合[pafy](https://github.com/mps-youtube/pafy),您可以获取频道上的所有视频。 – Jabba 2015-07-08 18:08:33

+2

这不适用于PyCon 2015频道,甚至在git上提到的例子,它只是说没有找到频道。难道我做错了什么。 – 2015-11-05 07:34:29

在YouTube API变更后,最大K公司的答案是行不通的。作为替代,下面的功能提供给定频道中的YouTube视频列表。请注意,您需要API Key才能正常工作。

import urllib 
import json 

def get_all_video_in_channel(channel_id): 
    api_key = YOUR API KEY 

    base_video_url = 'https://www.youtube.com/watch?v=' 
    base_search_url = 'https://www.googleapis.com/youtube/v3/search?' 

    first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id) 

    video_links = [] 
    url = first_url 
    while True: 
     inp = urllib.urlopen(url) 
     resp = json.load(inp) 

     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 
    return video_links