如何在Jenkins虚拟机环境中实现Selenium+Pytest测试录屏?
Jenkins虚拟机环境实现测试录屏的解决方案
你的代码在PC上正常但Jenkins虚拟机失效,核心原因是Jenkins虚拟机多为无头(Headless)环境,没有真实的图形显示会话,而pyautogui依赖系统显示服务才能完成截图操作,导致录屏无内容。下面是几种可行的解决办法:
1. 用Xvfb创建虚拟显示会话
Xvfb是一款虚拟X11显示服务器,能在无物理显示屏的环境中模拟图形界面,让依赖显示的工具正常工作:
- 先在Jenkins节点安装Xvfb:
# Debian/Ubuntu系统 sudo apt-get install xvfb # CentOS/RHEL系统 sudo yum install xorg-x11-server-Xvfb - 在Jenkins流水线的测试执行阶段前,添加启动虚拟显示的命令:
export DISPLAY=:99 Xvfb :99 -screen 0 1920x1080x24 & - 确保Python代码能读取到
DISPLAY环境变量,pyautogui会自动关联这个虚拟显示,无需修改原有核心逻辑。
2. 替换录屏方式,适配无头场景
如果你的测试是Web自动化类型(比如基于Selenium),可以直接使用针对测试框架的录屏工具,无需依赖系统截图:
- 例如使用
selenium-video-recorder库,它直接捕获浏览器渲染内容,不依赖虚拟显示:from selenium_video_recorder.video_recorder import VideoRecorder from allure_commons.types import AttachmentType import os def test_web_recording(driver): video_folder = "./test_videos" os.makedirs(video_folder, exist_ok=True) # 初始化录屏器,关联浏览器驱动 recorder = VideoRecorder(driver, save_path=video_folder) recorder.start() # 这里执行你的测试步骤 driver.get("https://example.com") recorder.stop() # 将录屏文件附加到Allure报告 allure.attach.file(recorder.video_path, name="Test_Video", attachment_type=AttachmentType.MP4)
3. 调整现有代码适配虚拟显示
如果必须保留pyautogui的录屏逻辑,需要优化代码适配虚拟显示的分辨率:
- 去掉硬编码的
resolution = (1920, 1080),改用动态获取的屏幕尺寸,避免和虚拟显示分辨率不匹配:def start_video_recording(): os.makedirs(video_folder, exist_ok=True) screen_width, screen_height = pyautogui.size() print("Screen resolution size: {}x{}".format(screen_width, screen_height)) print("Video Recording Started") global video_recording # 改用动态获取的分辨率 resolution = (screen_width, screen_height) codec = cv2.VideoWriter_fourcc(*"mp4v") fps = 60.0 timestamp = datetime.now().strftime("%d%m%Y_%H%M%S") filename_video = os.path.join(video_folder, f"video_{timestamp}.MP4") out = cv2.VideoWriter(filename_video, codec, fps, resolution) while video_recording: img = pyautogui.screenshot() frame = np.array(img) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) out.write(frame) if cv2.waitKey(1) == ord('q'): break out.release() if filename_video is not None: allure.attach.file(filename_video, name="Test_Video", attachment_type=AttachmentType.MP4) print(f"Video attached: {filename_video}") - 同时要确保Jenkins执行用户拥有访问Xvfb显示会话的权限,必要时可通过
xauth工具配置权限。
额外注意点
- 确保Jenkins虚拟机已安装所有依赖库:
opencv-python、pyautogui、numpy、allure-pytest等。 - 录屏文件生成后,检查Jenkins用户对文件的读写权限,避免Allure无法正常附加文件。
内容的提问来源于stack exchange,提问作者Sehaj Paul Singh
相关产品推荐
相关产品推荐

