提示:前言
Python爬虫之findall和lxml
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:以下是本篇文章正文内容,下面案例可供参考
import pprint
from lxml import etree
import requests
import re
import json
设置headers
# ffmpeg 视频名字 音频名字 输出文件名字 i -cc
headers = {
"referer":"https://www.bilibili.com/",
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
}
下载B站中的视频
“https://www.bilibili.com/video/BV1kd4y157X9”
url = "https://www.bilibili.com/video/BV1kd4y157X9"
r = requests.get(url, headers=headers)
提取视频和音频的播放地址
# 提取视频和音频的播放地址
info = re.findall("window.__playinfo__=(.*?)", r.text)[0]
info = json.loads(info)
video_url = info["data"]["dash"]["video"][0]["baseUrl"]
audio_url = info["data"]["dash"]["audio"][0]["baseUrl"]
解析视频名字:
html = etree.HTML(r.text)
filename = html.xpath("//h1/text()")[0].replace(" ", "")
分别下载视频和音频
# 分别下载视频和音频
print("开始下载")
video_content = requests.get(video_url, headers=headers).content
audio_content = requests.get(audio_url, headers=headers).content
with open(f"video/{filename}.mp4", "wb") as f:
f.write(video_content)
print("已下载视频部分")
with open(f"video/{filename}.mp3", "wb") as f:
f.write(audio_content)
print("已下载音频部分")
from moviepy import *
from moviepy.editorimport *
video_path = "video/{filename}.mp4"
audio_path = "video/{filename}.mp3"
# 读入视频
video = VideoFileClip(video_path)
# 提取音轨
audio = AudioFileClip(audio_path)
# 将音轨合并到视频中
video = video.set_audio(audio)
# 输出
video.write_videofile(f"video/{filename}(含音频).mp4")
参考链接:
http://www.cppcns.com/jiaoben/python/451984.html
http://www.360doc.com/content/22/0127/21/360939_1015148940.shtml