我需要逐页获取YouTube频道中的所有视频。 YouTube API允许最多可获得50个视频。 现在,我只使用Django分页获得25个视频并在页面中打印。如何在网页上打印来自YouTube的所有视频?
views.py for video view:
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>
我想手动计算视频数量并将其计入页数,但我不知道如何实现它
答案 0 :(得分:0)
好吧,所以第一部分:获取视频(您将需要一个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友好的东西并使用它