python:获取频道的所有YouTube视频链接

19 投票
8 回答
51762 浏览
提问于 2025-04-17 19:41

我想获取一个特定频道的所有视频链接。我觉得用Python或Java处理JSON数据是个不错的选择。我可以用下面的代码获取最新的视频,但我该怎么才能获取所有的视频链接(超过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

8 个回答

19

在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
24

简短回答:

这里有一个可以帮你解决问题的库。

pip install scrapetube

import scrapetube

videos = scrapetube.get_channel("UC9-y-6csu5WGm29I7JiwpnA")

for video in videos:
    print(video['videoId'])

详细回答:

上面提到的这个模块是我自己做的,因为找不到其他合适的解决方案。以下是我尝试过的方法:

  1. 使用Selenium。这个方法能用,但有三个大缺点:1. 需要安装网页浏览器和驱动程序。2. 对CPU和内存的要求很高。3. 处理大频道时效果不好。
  2. 使用youtube-dl。像这样:
import youtube_dl
    youtube_dl_options = {
        'skip_download': True,
        'ignoreerrors': True
    }
    with youtube_dl.YoutubeDL(youtube_dl_options) as ydl:
        videos = ydl.extract_info(f'https://www.youtube.com/channel/{channel_id}/videos')

这个方法对小频道有效,但对于大频道,我会因为在短时间内发送太多请求而被YouTube封锁(因为youtube-dl会为频道中的每个视频下载更多信息)。

所以我制作了这个库 scrapetube,它使用网络API来获取所有视频。

13

你可以把最大结果数从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

撰写回答