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

新手上路,请多包涵

我想获取特定频道的所有视频网址。我认为 json 与 python 或 java 将是一个不错的选择。我可以使用以下代码获取最新视频,但如何获取所有视频链接(>500)?

 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

原文由 Johnny 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

将 max-results 从 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

原文由 max k. 发布,翻译遵循 CC BY-SA 3.0 许可协议

youtube API 更改后,max k. 的答案不起作用。作为替代,下面的函数提供了给定频道中的 YouTube 视频列表。请注意,您需要一个 API 密钥 才能运行。

 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

原文由 Stian 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题