从YouTube频道逐页获取所有视频
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从YouTube频道逐页获取所有视频相关的知识,希望对你有一定的参考价值。
我需要从YouTube频道逐页获取所有视频。 YouTube API最多允许50个视频。现在,使用Django分页,我仅获得25个视频并在页面中打印。如何在页面上打印YouTube上的所有视频?
用于视频观看的views.py:
YOUTUBE_VIDEO_URL = "https://gdata.youtube.com/feeds/api/videos?author=*****&orderby=updated&v=2&alt=jsonc"
class VideoListView(ListView):
template_name = "video/list.html"
context_object_name = 'videos'
paginate_by = 12
def get_queryset(self, **kwargs):
request = requests.get(settings.YOUTUBE_VIDEO_URL)
data_about = simplejson.loads(request.text)
video_list = []
for item in data_about['data']['items']:
video_list.append(item)
return video_list
查看:
<div id="list_articles">
% if videos %
% for video in videos %
<div class="article">
<iframe src="http://www.youtube.com/embed/ video.id "
width="300" height="225" frameborder="0" allowfullscreen></iframe>
<h2><a class="popup-youtube"
href="http://www.youtube.com/watch?v= video.id "> video.title </a></h2>
</div>
% endfor %
% else %
<div class="article">
<p>Nothing</p>
</div>
% endif %
</div>
% if is_paginated %
<div id="pages">
<p> Pages:% for num in page_obj.paginator.page_range %
% ifequal num page_obj.number %
<span class="current"><b> num </b></span>
% else %
<a href="?page= num "> num </a>
% endifequal %
% endfor %
</p>
我想手动获取视频计数并将其按页数划分,但我不知道如何实现
答案
好吧,所以第一部分:获取视频(您将需要一个api键,对于常规使用可能需要多个):
这是python,但您可以将其转换为任意内容,只要它可以发送GET请求即可:
注意:抄送定义了是否查找常见的创意视频您也可以使用搜索查找视频
from requests import get
from random import choice
useSearch = True
fname = "output"
if useSearch :
cc = False
searchTerm = ""
apiKeys = []
apiKey = choice(apiKeys)
url = "https://www.googleapis.com/youtube/v3/search"
token = ""
rDone = 0
videos = []
searching = True
if cc :
searchTerm = searchTerm + "&videoLicense=creativeCommon&type=video"
while searching :
print(url + "?key=" + apiKey + "&q=" + searchTerm + "&part=id&maxResults=50&pageToken=" + token)
y = get(url + "?key=" + apiKey + "&q=" + searchTerm + "&part=id&maxResults=50&pageToken=" + token).json()
if y['kind'] == "youtube#searchListResponse" :
for x in y['items'] :
if x['id']['kind'] == "youtube#video" :
videos.append(x['id']['videoId'])
rDone = rDone + int(y['pageInfo']['resultsPerPage'])
if int(y['pageInfo']['totalResults']) <= rDone :
searching = False
elif int(y['pageInfo']['resultsPerPage']) > int(y['pageInfo']['totalResults']) :
searching = False
else :
try :
token = y['nextPageToken']
except :
searching = False
else :
cc = False
channelID = ""
apiKeys = ["AIzaSyBTV_7FVKuJBvFEPo1ZkLtXSl7w2Ulg6XY", "AIzaSyAzwkMIvLFYTYz5uHv-Idmq68Er_DzOEkI", "AIzaSyDPGSYUScf6j9A7uE1pWaXxK9j9TCGZbEs"]
apiKey = choice(apiKeys)
url = "https://www.googleapis.com/youtube/v3/search"
token = ""
rDone = 0
videos = []
searching = True
if cc :
channelID = channelID + "&videoLicense=creativeCommon&type=video"
while searching :
print(url + "?key=" + apiKey + "&channelId=" + channelID + "&part=id&order=date&maxResults=50&pageToken=" + token)
y = get(url + "?key=" + apiKey + "&channelId=" + channelID + "&part=id&order=date&maxResults=50&pageToken=" + token).json()
if y['kind'] == "youtube#searchListResponse" :
for x in y['items'] :
if x['id']['kind'] == "youtube#video" :
videos.append(x['id']['videoId'])
rDone = rDone + int(y['pageInfo']['resultsPerPage'])
if int(y['pageInfo']['totalResults']) <= rDone :
searching = False
elif int(y['pageInfo']['resultsPerPage']) > int(y['pageInfo']['totalResults']) :
searching = False
else :
try :
token = y['nextPageToken']
except :
searching = False
file = open(fname + ".txt", "w+")
for index in range(len(videos)) :
video = videos[index]
if len(videos) - 1 == index :
file.write(video)
else :
file.write(video + "\n")
file.close()
接下来,您需要将输出分成列表。使用这样的东西:
ls = open("../output.txt", "r").read().split("\n")
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
pages = list(chunks(ls, 10))
页面[0]将是第一页
如果您想将其用于网页,则可以将其变成php友好的东西并使用它
以上是关于从YouTube频道逐页获取所有视频的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 YouTube Data API v3 从我自己的 YouTube 频道获取所有视频