整页截图、元素截图及Base64格式输出等操作
演示 Selenium 截图的 3 类 API + 1 个 Selenium 4 新功能,自动化测试排查失败现场的必备技能。本页可以实时模拟浏览器视口截图和元素级截图效果。
截图方式对比:
driver.save_screenshot("shot.png") → 直接存文件,最简单driver.get_screenshot_as_file(path) → 和上面一样,返回 True/Falsedriver.get_screenshot_as_base64() → 返回 base64 字符串,可嵌进 HTML 报告driver.get_screenshot_as_png() → 返回 PNG 二进制字节,open(wb).write() 存el.save_screenshot("logo.png") → Selenium 4 新功能,只截某个元素!⚠️ 关键限制:Selenium 默认只能截 视口(屏幕可见区域)。要截整页需用 CDP:driver.execute_cdp_cmd("Page.captureScreenshot", {"captureBeyondViewport": True})
save_screenshot / get_screenshot_as_base64 / base64.b64decode / os.path.exists / WebElement.screenshot
# 快速参考 import os, base64 ok = driver.save_screenshot("./shot.png") assert ok and os.path.exists("./shot.png") b64 = driver.get_screenshot_as_base64() with open("./shot_b64.png", "wb") as f: f.write(base64.b64decode(b64)) # Selenium 4.0+ 进阶:元素级截图 driver.find_element(By.ID, "shot_target_card").screenshot("./shot_ele.png")
save_screenshot("shot.png") 保存整张页面,断言返回值为 True,用 os.path.exists() 验证文件已生成,os.path.getsize() 断言大小 > 0,扩展名为 .pngget_screenshot_as_base64() 获取 base64 编码,base64.b64decode() 解码后写入 .png 文件#shot_target_card 卡片后调用元素级 .screenshot("./shot_ele.png") 单独截取该元素(Selenium 4.0+ 新增 API)
操作步骤:
① 使用 driver.save_screenshot("shot.png") 保存整张页面截图,断言返回值为 True,用 os.path.exists() 验证文件存在,os.path.getsize() 断言大小 > 0,扩展名为 .png。
② 使用 driver.get_screenshot_as_base64() 获取 base64 编码字符串,用 base64.b64decode() 解码后以二进制写入 shot_b64.png,断言文件已生成且大小 > 0。
③ 进阶:定位页面上的某个元素(如下方的「截图目标卡片」#shot_target_card),使用 element.screenshot("ele.png") 单独截取该元素(Selenium 4.0+ 新增 API)。
截图预览区 — 使用 Selenium save_screenshot() 即可将整张页面保存为 PNG
真实代码示例:driver.save_screenshot("./shots/ex4.png")
# 练习 8 参考答案 import os from selenium.webdriver.common.by import By # 确保已打开页面 if "浏览器操作练习" not in driver.title: driver.get("file:///f:/autotest_project/browser_op_practice.html") # 1. save_screenshot 截图整张页面并验证文件 shot_path = "./shot.png" ok = driver.save_screenshot(shot_path) print(f"save_screenshot 返回值:{ok}") assert ok is True assert os.path.exists(shot_path), f"截图文件不存在: {shot_path}" assert os.path.getsize(shot_path) > 0, "截图文件大小为 0" assert shot_path.endswith(".png"), "截图文件扩展名应为 .png" print(f"截图已保存且验证通过,文件大小:{os.path.getsize(shot_path)} bytes") # 2. get_screenshot_as_base64 获取 base64 并保存为文件 import base64 b64_str = driver.get_screenshot_as_base64() assert len(b64_str) > 0, "base64 字符串为空" b64_path = "./shot_b64.png" with open(b64_path, "wb") as f: f.write(base64.b64decode(b64_str)) assert os.path.exists(b64_path), f"base64 截图文件不存在: {b64_path}" assert os.path.getsize(b64_path) > 0, "base64 截图文件大小为 0" print(f"base64 截图已保存:{b64_path},大小:{os.path.getsize(b64_path)} bytes") # 3. 进阶:Selenium 4.0+ 元素级截图 card = driver.find_element(By.ID, "shot_target_card") card.screenshot("./shot_ele.png") assert os.path.exists("./shot_ele.png") and os.path.getsize("./shot_ele.png") > 0 print("✅ 元素级截图成功:shot_ele.png") print("✅ 练习 8 所有断言通过!")