使用Python在selenium中实现动态截图
前言
在做自动化中,有些页面去截图时,可能截图的结果仅仅是最后的结果,而中间的一些变化步骤,是无法关注到的,这就给定位问题造成了麻烦。因此有时进行动态截图就是有必要的。
分析
那么如何实现动态截图的。经过了解,很多方法就是,逐帧截图图片,每一帧有持续时长,然后把这些图片合成为一张,这样就形成了一个动态图片。
实现
我们用一个函数来实现这个操作,包括以下参数:
url:需要截取的目标网页
output_path:输出文件路径
element_selector:定位需要截图的区域(为 None 时截图整个页面)
duration:截图总时长
frame_interval:每帧截取间隔时长
那么最终结果就是:
1 from selenium import webdriver 2 from selenium.webdriver.chrome.service import Service 3 from selenium.webdriver.chrome.options import Options 4 from PIL import Image, ImageSequence 5 import time 6 import os 7 8 9 def capture_dynamic_gif(url, output_path, element_selector=None, duration=5, frame_interval=0.2): 10 """ 11 动态截图一定时间内的变化,并生成 GIF 图像 12 :param url: 目标网页 URL 13 :param output_path: GIF 文件保存路径 14 :param element_selector: CSS 选择器,定位需要截图的区域(为 None 时截图整个页面) 15 :param duration: 总截图时间(秒) 16 :param frame_interval: 截图间隔时间(秒) 17 """ 18 # ChromeDriver 路径 19 webdriver_path = r"C:\Program Files\Google\Chrome\Application\chromedriver.exe" # 替换为你的 ChromeDriver 路径 20 21 # 配置 Chrome 浏览器选项 22 chrome_options = Options() 23 # chrome_options.add_argument("--headless") # 无头模式运行 24 chrome_options.add_argument("--disable-gpu") 25 26 # 启动 WebDriver 27 service = Service(webdriver_path) 28 driver = webdriver.Chrome(service=service, options=chrome_options) 29 30 # 保存截图的临时文件夹 31 temp_dir = "picture" 32 os.makedirs(temp_dir, exist_ok=True) 33 34 frames = [] # 用于保存所有截图的帧 35 36 try: 37 # 加载目标网页 38 driver.get(url) 39 driver.maximize_window() 40 time.sleep(5) # 等待页面加载 41 start_time = time.time() 42 43 while time.time() - start_time < duration: 44 # 截取整个页面或特定元素 45 if element_selector is None: 46 screenshot_path = os.path.join(temp_dir, f"screenshot_{int(time.time() * 1000)}.png") 47 driver.save_screenshot(screenshot_path) 48 frames.append(Image.open(screenshot_path)) 49 else: 50 element = driver.find_element("css selector", element_selector) 51 52 # 截取整个页面的截图 53 driver.save_screenshot("temp_full_page.png") 54 55 # 获取元素的位置和大小 56 location = element.location 57 size = element.size 58 59 # 使用 Pillow 裁剪特定区域 60 x = location['x'] 61 y = location['y'] 62 width = location['x'] + size['width'] 63 height = location['y'] + size['height'] 64 65 # 打开保存的全页面截图并裁剪 66 with Image.open("temp_full_page.png") as img: 67 cropped_image = img.crop((x, y, width, height)) 68 screenshot_path = os.path.join(temp_dir, f"screenshot_{int(time.time() * 1000)}.png") 69 cropped_image.save(screenshot_path) 70 frames.append(cropped_image) 71 72 print(f"截取了一帧: {screenshot_path}") 73 time.sleep(frame_interval) # 等待下一个截图时机 74 75 # 生成 GIF 动态图片 76 if frames: 77 frames[0].save( 78 output_path, save_all=True, append_images=frames[1:], optimize=False, duration=int(frame_interval * 1000), loop=0 79 ) 80 print(f"GIF 保存成功:{output_path}") 81 else: 82 print("未捕获到任何帧,无法生成 GIF") 83 84 except Exception as e: 85 print("截图失败:", e) 86 87 finally: 88 # 清理临时文件 89 driver.quit() 90 for f in os.listdir(temp_dir): 91 os.remove(os.path.join(temp_dir, f)) 92 os.rmdir(temp_dir) 93 94 95 # 示例用法 96 if __name__ == "__main__": 97 # 截取整个页面变化生成 GIF 98 # capture_dynamic_gif("https://www.ihuiwa.com/workspace/ai-video/custom-action?huiwaInviteCode=EMRCAL", "dynamic_screenshot.gif", duration=10, frame_interval=0.1) 99 100 # 截取页面中特定元素变化生成 GIF 101 capture_dynamic_gif("https://www.ihuiwa.com/workspace/ai-video/custom-action?huiwaInviteCode=EMRCAL", "dynamic_element_screenshot.gif", element_selector=".scroll-content .ant-result-icon", duration=5, frame_interval=0.3)