import requests
import json
from urllib import parse
import re
# 抖音视频的URL : Request URL:
url="https://www.iesdouyin.com/web/api/v2/aweme/post/?sec_uid=MS4wLjABAAAAPiYAuTiuaI39UV-QJtyFYdT74-Y0NdNOddeS3JUaeWg&count=21&max_cursor=0&_signature=xHcvZwAApmfZvSVp7lyHfMR3L3"

headers = {
'User-Agent':"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
}
#调用requests中的get获取抖音作者主页的网页链接
r = requests.get(url=url, headers=headers,stream=True)
#输出访问状态,如为<200>即为访问成功
print("初始访问状态:",r)
#使用json解析获取的网页内容
data_json = json.loads(r.text)
#使用json解析网页后,data_json的内容为dict格式,我们可以通过以下方式查看健名
#print(data_json)
path='/'
for i in range(len(data_json['aweme_list'])):
#url_1为我们获取的视频链接
url_1 = data_json['aweme_list'][i]['video']['play_addr_lowbr']['url_list'][0]
#t为我们获取的视频标题
t = data_json['aweme_list'][i]['desc']
# requests发送浏览器发送get请求,得到数据
r = requests.get(url=url_1, headers=headers,stream=True)
print(r) #输出r访问状态
# 获取数据的二进制长度
reponse_body_lenth = int(r.headers.get("Content-Length"))
# 打印数据的长度
print("视频的数据长度为:", reponse_body_lenth)
#path_1为完整文件保存路径
path_1 = path+t+'.mp4'
#去除文件名中特殊字符否则报错
rstr = r"[\/\\\:;\*#¥%$!@^……&()\?\"\<\>\|]" # '/ \ : * ? " < > |'
path_1 = re.sub(rstr, "", path_1) # 替换为""
# 保存抖音视频mp4格式,二进制读取
with open(path_1, "wb") as xh:
# 先定义初始进度为0
write_all = 0
for chunk in r.iter_content(chunk_size=1000000):
write_all += xh.write(chunk)
# 打印下载进度
print("下载进度:%02.6f%%" % (100 * write_all / reponse_body_lenth))