画面录制:Playwright 内置了屏幕录制功能,可以将浏览器窗口内容录制为视频文件。
声音录制:标准的 Playwright 录制功能不支持捕获网页内的音频。
要录制声音,需要结合其他工具或方法,例如ffmpeg+虚拟音频设备VB-Audio捕获系统音频
在 Windows 上,你需要安装 VB-Audio 虚拟设备
在 macOS 上,你可以使用 Soundflower 或 BlackHole 等工具
在 Linux 上,你可以使用 PulseAudio 或 JACK
完整代码
import os
import subprocess
from playwright.sync_api import sync_playwright
def record_webpage_with_audio(url, output_file="recording.mp4", duration=10):
# 创建临时目录存储录制文件
temp_dir = "temp_recording"
os.makedirs(temp_dir, exist_ok=True)
# 启动系统音频捕获(需要安装额外工具如ffmpeg和系统音频捕获工具)
# 这里使用系统命令行调用,实际使用时可能需要调整参数
audio_process = None
try:
# 启动音频捕获进程(Windows示例,使用VB-Audio虚拟设备)
audio_file = os.path.join(temp_dir, "audio.wav")
audio_process = subprocess.Popen(
[
"ffmpeg", "-y", "-f", "dshow", "-i", "audio=virtual-audio-capturer",
"-t", str(duration), audio_file
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# 使用Playwright录制视频
with sync_playwright() as p:
browser = p.chromium.launch(
headless=False,
args=[
'--autoplay-policy=no-user-gesture-required',
'--disable-features=PreloadMediaEngagementData,AutoplayIgnoreWebAudio'
]
)
# 创建上下文并开始录制
context = browser.new_context(
record_video_dir=temp_dir,
record_video_size={"width": 1280, "height": 720}
)
page = context.new_page()
page.goto(url)
# 等待页面加载
page.wait_for_load_state("networkidle")
# 确保音频自动播放
page.evaluate('''() => {
const audioElements = document.querySelectorAll('audio');
audioElements.forEach(audio => {
audio.play().catch(e => console.log('播放失败:', e));
});
}''')
# 等待指定的录制时间
page.wait_for_timeout(duration * 1000)
# 获取录制的视频文件路径(更新的API调用方式)
# 保存page对象以便在context关闭后访问视频
video_page = page
# 关闭浏览器和上下文
context.close()
browser.close()
# 在关闭context后获取视频路径
video_path = video_page.video.path()
# 等待音频录制完成
if audio_process:
audio_process.wait()
# 合并视频和音频
video_output = os.path.join(temp_dir, "video.webm")
os.rename(video_path, video_output)
final_output = output_file
subprocess.run([
"ffmpeg", "-y", "-i", video_output, "-i", audio_file,
"-c:v", "copy", "-c:a", "aac", final_output
])
print(f"录制完成,已保存到: {final_output}")
except Exception as e:
print(f"录制过程中发生错误: {e}")
finally:
# 清理临时文件
if audio_process and audio_process.poll() is None:
audio_process.terminate()
# 这里可以添加删除临时目录的代码
# 使用示例
if __name__ == "__main__":
record_webpage_with_audio(
url="https://example.com", # 替换为你要录制的网站
output_file="webpage_recording.mp4",
duration=20 # 录制时长(秒)
)
网友回复
如何让ai帮我自动在小红书或抖音上自动根据需求截流与潜在客户聊天拉客?
如果用go编写一个在virtualbox中启动的简单操作系统?
go如何搭建一个零信任网络?
如何用python实现一个公网代理访问软件?
如何用go实现一个公网代理访问软件?
如何用python实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
如何用go实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
何为Shadowsocks 代理?
python如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?
nodejs如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?


