【问题标题】:How can I get the duration of Youtube video with python?如何使用 python 获取 Youtube 视频的时长?
【发布时间】:2016-02-15 09:22:45
【问题描述】:

如何获取 Youtube 视频的时长?我正在尝试这个...

import gdata.youtube
import gdata.youtube.service

yt_service = gdata.youtube.service.YouTubeService()
entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')

print 'Video title: %s' % entry.media.title.text
print 'Video duration: %s' % entry.media.duration.seconds

控制台响应

Traceback (most recent call last):
  File "/Users/LearningAnalytics/Dropbox/testing/youtube.py", line 8, in <module>
    entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')
  File "/Library/Python/2.7/site-packages/gdata/youtube/service.py", line 210, in GetYouTubeVideoEntry
    return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
  File "/Library/Python/2.7/site-packages/gdata/service.py", line 1107, in Get
    'reason': server_response.reason, 'body': result_body}
gdata.service.RequestError: {'status': 410, 'body': 'No longer available', 'reason': 'Gone'}

【问题讨论】:

  • 您是否尝试过使用其他视频 ID?
  • 410 错误意味着 youtube 端出了问题,而不是你的
  • 是的,我尝试使用不同的 id 并且不起作用
  • 知道@BansalUtkarsh 吗?
  • 试图在我的机器上复制错误

标签: python video youtube youtube-api youtube-data-api


【解决方案1】:

获取 youtube 视频时长的两种方法

第一种方式:


使用 python 和 V3 youtube api,这是每个视频的方式。您需要 API 密钥,您可以在这里获取:https://console.developers.google.com/

# -*- coding: utf-8 -*-
import json
import urllib

video_id="6_zn4WCeX0o"
api_key="Your API KEY replace it!"
searchUrl="https://www.googleapis.com/youtube/v3/videos?id="+video_id+"&key="+api_key+"&part=contentDetails"
response = urllib.urlopen(searchUrl).read()
data = json.loads(response)
all_data=data['items']
contentDetails=all_data[0]['contentDetails']
duration=contentDetails['duration']
print duration

控制台响应:

>>>PT6M22S

对应于 6 分 22 秒。

第二种方式:


另一种但不适用于所有视频的方法是使用 pafy 外部包:

import pafy

url = "http://www.youtube.com/watch?v=cyMHZVT91Dw"
video = pafy.new(url)
print video.length

我从https://pypi.python.org/pypi/pafy/0.3.42安装了pafy

【讨论】:

  • 如果需要,您可以使用duration = isodate.parse_duration(duration) 解析ISO 持续时间,然后使用isodate 包解析video_dur = duration.total_seconds()
【解决方案2】:

你也可以试试下面的

search_url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={YT_KEY}&part=contentDetails'
req = urllib.request.Request(search_url)
response = urllib.request.urlopen(req).read().decode('utf-8')
data = json.loads(response)
all_data = data['items']
duration = all_data[0]['contentDetails']['duration']

minutes = int(duration[2:].split('M')[0])
seconds = int(duration[-3:-1])

这将使用 utf-8 编码对响应进行解码。 这让我可以将它存储到一个 json 变量中。

【讨论】:

    猜你喜欢
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2015-09-06
    • 1970-01-01
    • 2015-12-07
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多