根据抖音分享的短链接,批量下载抖音短视频
只需要在数组 urlData[ ] 中添加需要下载的链接即可
注意:平台有反爬机制,批量下载的时候尽量加随机延迟,避免网站有反爬机制封掉ip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# -*- coding=utf-8 -*-
# DY去水印批量下载
import requests
import re
from time import time, sleep

header = {
"User-Agent": "Mozilla/5.0 (Linux; Android 8.0.0; EVA-AL10 Build/HUAWEIEVA-AL10;\
wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/76.0.3809.89\
Mobile Safari/537.36 T7/11.20 SP-engine/2.16.0 baiduboxapp/11.20.0.14 (Baidu; P1 8.0.0)",
}

# 根据分享链接,重定向后获取视频id
def getVideoId(urlShare):
# 先访问传入的链接,获取跳转后的链接(针对短连接)
# 获取重定向的链接
redirectUrl = requests.get(url=urlShare, headers=header).url
# 返回的链接应该是 https://www.iesdouyin.com/share/video/视频ID/ 通过正则寻找视频id
pat = re.compile(r"/video/(\d+)/")
result = pat.search(redirectUrl) # 寻找的结果
if result == None:
print("视频id获取失败")
id = "0" # 失败返回0
else:
id = pat.search(redirectUrl).group(1)
return id

# 返回视频无水印链接和描述和音频地址,传入视频id
def getDouyinVideoUrl(dyVideoId):
b_time = time()
# 网页抓的视频接口
url = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + str(dyVideoId)
# 视频接口json解析 取得无水印的视频链接 但是没跳转
resp = requests.get(url, headers=header).json()
# print(resp)
title = resp["item_list"][0]["desc"]
wm_url = resp["item_list"][0]["video"]["play_addr"]["url_list"][0].replace('playwm', 'play')
mp3_url = resp["item_list"][0]["music"]["play_url"]["uri"]
photo_url = resp["item_list"][0]["video"]["origin_cover"]["url_list"][0]
# 访问无水印链接,获取跳转后的链接要用安卓手机ua访问
videoUrl = requests.get(url=wm_url, headers=header).url
e_time = time()
print("视频解析成功, 耗时:", str(round(e_time - b_time, 2)) + "s")
return title, videoUrl, mp3_url, photo_url

# 写入视频加上描述
def writeVideo(url, downloadPath, name):
b_time = time()
video = requests.get(url, headers=header).content
path = downloadPath + name + ".mp4"
with open(path, "wb") as f:
f.write(video)
e_time = time()
print("视频: ", name, "下载成功, 耗时:", str(round(e_time - b_time, 2)) + "s")

if __name__ == '__main__':
# 下载存放路径
downloadPath = r"/Users/renyuxin/Downloads/"
# 抖音分享链接
urlData = ["https://v.douyin.com/jDvWosy/", "https://v.douyin.com/jDv3mQX/"]

# 遍历下载
for index in urlData:
# 开始下载时间
startTime = time()
# 根据分享链接,重定向后获取视频id
dyVideoId = getVideoId(index)
# 获取视频内容
title, video_url, mp3_url, photo_url = getDouyinVideoUrl(dyVideoId)
print("\t视频标题:", title, "\n\t链接:", video_url, "\n\t音频链接:", mp3_url, "\n\t封面图:", photo_url)
# 自定义视频名称
writeVideo(video_url, downloadPath, title)
# 结束下载时间
endTime = time()
print("下载总耗时:", str(round(endTime - startTime, 2))+"s", "下载第", index, "个")
print("\n\n")