内附接口,修改目标url即可下载目标视频
使用者需自行下载ffmpeg并修改代码中的路径
(仅做学习,如有侵权,请私信)
[Python] 纯文本查看 复制代码 import os
import re
import json
import subprocess
import requests
import fake_useragent
from lxml import etree
ua = fake_useragent.UserAgent().random
headers = {
'referer': 'https://www.bilibili.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}
def get_url(url):
# 爬取视频页网页源代码
r = requests.get(url, headers=headers)
# 提取视频和音频的播放地址
info = re.findall('window.__playinfo__=(.*?)</script>', r.text)[0]
video_url = json.loads(info)['data']['dash']['video'][0]['baseUrl']
audio_url = json.loads(info)['data']['dash']['audio'][0]['baseUrl']
html = etree.HTML(r.text)
filename = html.xpath('//h1/text()')[0]
return filename, video_url, audio_url
# 下载并保存音频和视频
def download(name, video_url, audio_url):
video_content = requests.get(video_url, headers=headers).content
audio_content = requests.get(audio_url, headers=headers).content
path = os.getcwd()
with open(f'{path}/{name}.mp4', 'wb') as f:
f.write(video_content)
print("已下载视频部分")
with open(f'{path}/{name}.mp3', 'wb') as f:
f.write(audio_content)
print("已下载音频部分")
# 合并音频和视频
def combine(name):
path = os.getcwd()
cmd = [
r"C:\download_solftware\ffmpeg-7.0.2-full_build\bin\ffmpeg", //自行下载,并修改此处路径
"-i", f"{path}\\{name}.mp4",
"-i", f"{path}\\{name}.mp3",
"-c:v", "copy",
"-c:a", "aac",
"-strict", "experimental",
f"{path}\\output-{name}.mp4"
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("已完成合并")
# 删除源文件
os.remove(f"{path}\\{name}.mp4")
os.remove(f"{path}\\{name}.mp3")
if __name__ == '__main__':
url = 'https://www.bilibili.com/video/BV1Tf421i7fV/?spm_id_from=333.1007.tianma.4-2-12.click'
name, video_url, audio_url = get_url(url)
download(name, video_url, audio_url)
combine(name) |