python批量下载快手个人主页短视频代码,2024年1月27日测试过了,如果日后更新了,私聊我
快手个人主页分视频和直播回放,直播回放的地址是m3u8,视频的地址是mp4
m3u8我采用的是hm3u8dl_cli这个库就行下载,带进度条
下面的代码需要以下模块
hm3u8dl_cli==0.4.9
Requests==2.31.0
代码跑通前操作
获取Cookie
开发者工具https://www.kuaishou.com/graphql 过滤这个数据包
复制Cookie里面的内容
放置Cookie
设置视频保存路径
import requests
import re
import time
import os
from datetime import datetime
from hm3u8dl_cli import m3u8download
from hm3u8dl_cli import idm
class KS(object):
def __init__(self,cookie,url,path):
#保存路径
if path:
#如果不存在该路径文件夹,则创建文件夹
if not os.path.exists(path):
os.makedirs(path)
self.path = path
else:
self.path = os.getcwd()
self.ksUserId = self.get_user_id(url)
self.ksHeaders = {
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Origin': 'https://www.kuaishou.com',
'Pragma': 'no-cache',
"Cookie":cookie,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
'accept': '*/*',
'content-type': 'application/json',
}
#解析url中的userid
def get_user_id(self,url):
match = re.search(r'profile/([^/]+)', url)
if match:
user_id = match.group(1)
print(user_id) # 输出: 3xcyy6cqjchvqqg
return user_id
else:
print("No user ID found in URL.")
return None
#获取url中的作者信息
def get_user_name(self):
json_data = {
'operationName': 'visionProfile',
'variables': {
'userId': self.ksUserId,
},
'query': 'query visionProfile($userId: String) {\n visionProfile(userId: $userId) {\n result\n hostName\n userProfile {\n ownerCount {\n fan\n photo\n follow\n photo_public\n __typename\n }\n profile {\n gender\n user_name\n user_id\n headurl\n user_text\n user_profile_bg_url\n __typename\n }\n isFollowing\n __typename\n }\n __typename\n }\n}\n',
}
response = requests.post('https://www.kuaishou.com/graphql', headers=self.ksHeaders, json=json_data).json()
#作者名"洛洛漫解"
user_name = response["data"]["visionProfile"]["userProfile"]["profile"]['user_name']
#作者个性签名 每日稀里糊涂更新宝子们频繁换漫画是因为 点赞不过万就很难申请后续版权所以如果喜欢就多多点赞吧所有解说漫画已授权
user_text = response["data"]["visionProfile"]["userProfile"]["profile"]['user_text']
#作者头像https://p2-pro.a.yximgs.com/uhead/AB/2022/06/17/15/BMjAyMjA2MTcxNTM2MjFfMjg4OTE4NDk3MF8xX2hkMjM2Xzc3Ng==_s.jpg
user_head_pic = response["data"]["visionProfile"]["userProfile"]["profile"]['headurl']
author_details = {
'author_name': user_name,
'author_signature': user_text,
'author_avatar_url': user_head_pic
}
#输出url信息
self.show_author_details(author_details)
return user_name
#输出显示url中的作者信息
def show_author_details(self,details):
# 显示作者的详细信息
print("\n作者信息:")
print(f"姓名: {details.get('author_name', '未知')}")
print(f"个性签名: {details.get('author_signature', '无')}")
print(f"头像URL: {details.get('author_avatar_url', '无')}\n")
#将mp4地址保存为视频
def save_mp4_to_file(self,name,title,url):
response = requests.get(url)
if(not os.path.exists(os.path.join(self.path,name))):
os.makedirs(os.path.join(self.path,name))
with open(os.path.join(self.path,name,re.sub(r'[\\/*?:"<>|\n]', '_', title)+".mp4"),"wb") as f:
f.write(response.content)
print(title+"下载完成")
#m3u8地址保存成视频
def save_m3u8_to_file(self,name,title,url):
m3u8download(m3u8url=url, title=re.sub(r'[\\/*?:"<>|\n]', '_', title),work_dir=os.path.join(self.path,name))
#mp4地址推送到idm下载保存成视频
def save_mp4_to_idm(self,title,url):
idm.download(url, save_name=re.sub(r'[\\/*?:"<>|\n]', '_', title) + '.mp4')
#获取视频标题和url
def get_video_data(self,name,pcursor):
json_data = {
'operationName': 'visionProfilePhotoList',
'variables': {
'userId': self.ksUserId,
'pcursor': pcursor,
'page': 'profile',
},
'query': 'fragment photoContent on PhotoEntity {\n __typename\n id\n duration\n caption\n originCaption\n likeCount\n viewCount\n commentCount\n realLikeCount\n coverUrl\n photoUrl\n photoH265Url\n manifest\n manifestH265\n videoResource\n coverUrls {\n url\n __typename\n }\n timestamp\n expTag\n animatedCoverUrl\n distance\n videoRatio\n liked\n stereoType\n profileUserTopPhoto\n musicBlocked\n}\n\nfragment recoPhotoFragment on recoPhotoEntity {\n __typename\n id\n duration\n caption\n originCaption\n likeCount\n viewCount\n commentCount\n realLikeCount\n coverUrl\n photoUrl\n photoH265Url\n manifest\n manifestH265\n videoResource\n coverUrls {\n url\n __typename\n }\n timestamp\n expTag\n animatedCoverUrl\n distance\n videoRatio\n liked\n stereoType\n profileUserTopPhoto\n musicBlocked\n}\n\nfragment feedContent on Feed {\n type\n author {\n id\n name\n headerUrl\n following\n headerUrls {\n url\n __typename\n }\n __typename\n }\n photo {\n ...photoContent\n ...recoPhotoFragment\n __typename\n }\n canAddComment\n llsid\n status\n currentPcursor\n tags {\n type\n name\n __typename\n }\n __typename\n}\n\nquery visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n result\n llsid\n webPageArea\n feeds {\n ...feedContent\n __typename\n }\n hostName\n pcursor\n __typename\n }\n}\n',
}
response = requests.post('https://www.kuaishou.com/graphql', headers=self.ksHeaders, json=json_data).json()
pcursor = response["data"]["visionProfilePhotoList"]["pcursor"]
for item in response["data"]["visionProfilePhotoList"]["feeds"]:
#视频标题
play_title = item["photo"]["caption"]
#mp4地址
#mp4_url = item["photo"]["manifest"]["adaptationSet"][0]["representation"][0]["backupUrl"][0]
play_url = item["photo"]["manifest"]["adaptationSet"][0]["representation"][0]["url"]
if ".m3u8" in play_url:
self.save_m3u8_to_file(name,play_title,play_url)
else:
#下面两种选其一
#requests下载
self.save_mp4_to_file(name,play_title,play_url)
#推送到idm
#self.save_mp4_to_idm(play_title,play_url)
return pcursor
#获取指定页数的视频数据,page=0或者为空则获取所有数据
def get_page_data(self,page=0):
pcursor = ""
#获取作者名
name = self.get_user_name()
if page == 0:
pages = 1000000 #搞一个不可能的数字,反正到时候会判断跳出
elif page >= 1:
pages = page
else:
print("page只能为0以上的数字")
return
index = 0
while True:
#到指定页数结束
if index >= pages:
break
#所有视频获取完毕结束
if pcursor == "no_more":
break
print(pcursor)
pcursor = self.get_video_data(name=name,pcursor=pcursor)
#防止滑块出现
time.sleep(20)
index += 1
if __name__ == "__main__":
profile_url = ["https://www.kuaishou.com/profile/3xdm7kf847weas2"]
for url in profile_url:
print("\n当前任务:"+url)
#by白白老师s
#QQ:2908436596
#cookie:cookie信息抓取快手https://www.kuaishou.com/graphql这个数据包的Cookie
#path:保存的路径,自己复制电脑上的路径
ks = KS(cookie="clientid=3;did=web_b3748731cd1742eeb10dc06d190f6574;client_key=65890b29;kpn=GAME_ZONE;kuaishou.live.web_st=ChRrdWFpc2hvdS5saXZlLndlYi5zdBKgAchZUDds6w0c617OQoSnJYE4feHhAsqmCd36QwUaQE1S9kjfKXxYjNQsxG3kDQ4Qt5_dlS56A2Vx7cejPVa_L6SOlk6uG3nB2PZr-eliPEBJhD341ScCeB24V5L40wu1jiij7gppA651eVhhs6QjAhewxqPxE55BVBRPi75ZCAg5rXR_HyAZomdaf_fD_BCd23TDCOvKNY0-EK8dfOZDxh4aEo_d-PiuxE4duU2DjxXdbB5BSiIgLsgTM7g6Z9_x0ou9RoiKobRGj7psBn_a2iypI-ngY_EoBTAB;kuaishou.live.web_ph=b07e306fd8aa91e512a4e417f3f76db688a2;userId=690466098;kuaishou.live.bfb1s=3e261140b0cf7444a0ba411c6f227d88",url=url,path=r"E:\BaiduNetdiskDownload\myPC\taobao\taobao\小白老师s开发的工具\项目\快手个人主页所有视频\video")
ks.get_page_data(0)
#防止滑块出现
time.sleep(20)