如果您使用的是 Python 3 或更新版本,则可以对YouTube v3 API URL 执行 GET 请求。为此,您需要在Google 控制台中启用YouTube v3 API,并且您需要在启用 YouTube v3 API 后创建 API 凭据。
下面的代码示例:
import json
import requests
YOUTUBE_ID = 'video_id_here'
API_KEY = 'your_youtube_v3_api_key'
url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={YOUTUBE_ID}&key={API_KEY}"
response = requests.get(url) # Perform the GET request
data = response.json() # Read the json response and convert it to a Python dictionary
length = data['items'][0]['contentDetails']['duration']
print(length)
或者作为一个可重用的函数:
import json
import requests
API_KEY = 'your_youtube_v3_api_key'
def get_youtube_video_duration(video_id):
url = f"https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id={video_id}&key={API_KEY}"
response = requests.get(url) # Perform the GET request
data = response.json() # Read the json response and convert it to a Python dictionary
return data['items'][0]['contentDetails']['duration']
duration = get_youtube_video_duration('your_video_id')
注意:如果您拥有视频,则只能从 API 获取 fileDetails,因此您需要使用与 YouTube 帐户相同的 Google 帐户作为 YouTube v3 API 密钥。
来自 Google 的响应将如下所示:
{
"kind": "youtube#videoListResponse",
"etag": "\"SJajsdhlkashdkahdkjahdskashd4/meCiVqMhpMVdDhIB-dj93JbqLBE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"SJZWTasdasd12389ausdkhaF94/aklshdaksdASDASddjsa12-18FQ\"",
"id": "your_video_id",
"contentDetails": {
"duration": "PT4M54S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": false,
"projection": "rectangular"
}
}
]
}
您的视频时长在哪里:PT4M54S
这意味着4 Minutes 54 Seconds
编辑:要将 YouTube 持续时间转换为秒,请参阅此答案:https ://stackoverflow.com/a/49976787/2074077
将时间转换为秒后,您可以使用 timedelta 将秒转换为您的格式。
from datetime import timedelta
time = timedelta(seconds=duration_in_seconds)
print(time)