📚博客主页:knighthood2001
✨公众号:认知up吧 (目前正在带领大家一起提升认知,感兴趣可以来围观一下)
🎃知识星球:【认知up吧|成长|副业】介绍
❤️如遇文章付费,可先看看我公众号中是否发布免费文章❤️
🙏笔者水平有限,欢迎各位大佬指点,相互学习进步!
全部代码
根据之前的文章,我们其实可以将其封装一下:
import requests
import re
import json
import os
import subprocess
# 函数:下载并保存视频和音频
def download_video_and_audio(url, headers):
try:
# 发送请求
response = requests.get(url=url, headers=headers)
response.raise_for_status() # 如果响应状态不是200,将抛出异常
html = response.text
# 解析数据:提取视频标题
title = re.findall('title="(.*?)"', html)[0]
print(f"视频标题: {title}")
# 解析视频信息
info = re.findall('window.__playinfo__=(.*?)</script>', html)[0]
json_data = json.loads(info)
# 提取视频链接和音频链接
video_url = json_data['data']['dash']['video'][0]['baseUrl']
audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
print(f"视频链接: {video_url}")
print(f"音频链接: {audio_url}")
# 下载视频内容
video_content = requests.get(url=video_url, headers=headers).content
# 下载音频内容
audio_content = requests.get(url=audio_url, headers=headers).content
if not os.path.exists('process_video'):
os.makedirs('process_video')
# 保存视频和音频数据
with open(f'process_video\\{title}.mp4', mode='wb') as v:
v.write(video_content)
with open(f'process_video\\{title}.mp3', mode='wb') as a:
a.write(audio_content)
print("视频音频下载完成!")
return title # 返回视频标题
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
except json.JSONDecodeError:
print("解析JSON时出错")
except Exception as e:
print(f"发生错误: {e}")
def merge_video(title):
print("开始合并视频...")
if not os.path.exists('finally_video'):
os.makedirs('finally_video')
# 合并成完整的视频内容
cmd = f'ffmpeg -hide_banner -i "process_video\\{title}.mp4" -i "process_video\\{title}.mp3" -c:v copy -c:a aac -strict experimental "finally_video\\{title}output.mp4"'
# 调用命令
subprocess.run(cmd)
if __name__ == '__main__':
# url = 'https://www.bilibili.com/video/BV1jt421c7yN/'
# url = 'https://www.bilibili.com/video/BV1vx421D7AP/?share_source=copy_web&vd_source=80a8f348074649de1e18f1345dee7db3'
# url = 'https://www.bilibili.com/video/BV1LT421S7sh'
url = 'https://www.bilibili.com/video/BV1H1421i7g6/?spm_id_from=333.999.0.0&vd_source=2ab95dfa6677af399778850be1824b83'
cookie = "buvid3=2844B77E-F527-FB05-1DF5-9FDF834AE3E888277infoc; b_nut=1709986388; i-wanna-go-back=-1; b_ut=7; _uuid=6577D687-BED9-9AE2-106A10-551210627F5AC88087infoc; enable_web_push=DISABLE; buvid4=5ED5B3A0-A998-7D47-3815-9AD9A1B27A4989131-024030912-0Fw3r6dKwZLwPoWOl%2F8HuA%3D%3D; CURRENT_FNVAL=4048; rpdid=|(u|Jmkkuukk0J'u~u|ulR~)~; header_theme_version=CLOSE; fingerprint=c27c0b59dd10dcdc4c14701a58f49669; buvid_fp_plain=undefined; LIVE_BUVID=AUTO6217111182462626; FEED_LIVE_VERSION=V_WATCHLATER_PIP_WINDOW3; bp_video_offset_691902317=925084214145056785; DedeUserID=691902317; DedeUserID__ckMd5=ead312019baad7ed; CURRENT_QUALITY=80; home_feed_column=4; PVID=1; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTY1NjYyODAsImlhdCI6MTcxNjMwNzAyMCwicGx0IjotMX0.4OcEc8xnUd8GPCTUkZM9UBejaRUnP0dhhjgL_DuFkgY; bili_ticket_expires=1716566220; SESSDATA=8abf5422%2C1731859084%2Ce2fa9%2A51CjD4mACI26GPIuH7wAe_rVLLXDq2VIckm2YvNvZpeMgzOMZCFVGss2CRvlLzxdOTmpASVk9nbUJtTU1QaWFqcUw1aWN5M19UMW0zdkhsZkdHRFdHdTZ1VVEzRUFmVUtKejhfS3FraFZ5WGM1OUstS1ZyeGRDTDhLM2Z1ekFuN09FcXFyaWIzWElnIIEC; bili_jct=ecb04e890e743862a38e01c7f37e08dd; bp_t_offset_691902317=934571401762832385; buvid_fp=c27c0b59dd10dcdc4c14701a58f49669; b_lsid=CB3EFD71_18FA63D003A; bmg_af_switch=1; bmg_src_def_domain=i0.hdslb.com; browser_resolution=675-639"
headers = {
"Referer": url,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Cookie": cookie
}
# 调用函数
title = download_video_and_audio(url, headers)
merge_video(title)
并且针对之前没有将视频音频合并,我这里也添加了这个功能。但是需要ffmpeg.exe,大家应该知道这是个音视频处理工具,很多软件,其实你下载下来,其中就会包含ffmpeg.exe。
需要ffmpeg.exe的可以上网找找,也可以私信我。
下载视频音频
首先,我构造了下载视频音频的函数,并且用try expect
进行解决报错。
下载下来的视频音频都会保存在process_video
文件夹中。
并且读取title
作为文件名称。
合并视频音频
接着,我将视频音频进行读取,并通过subprocess
库进行运行cmd命令,实现通过ffmpeg
将视频音频合并到指定目录下。
注意
- 你需要更改你要爬取的视频网址,以及更改cookie为你自己的cookie(cookie会过期,需要自己即使更新一下)。
- 你需要
ffmpeg.exe
,这是实现视频音频合并的关键。