使用 mss 库截取屏幕区域,配合 pillow 处理图像并生成 gif。核心做法是获取目标窗口的句柄和边界框,循环截取该矩形区域,将帧序列保存为动态 gif。

如何获取特定应用窗口的精确坐标
通过 pygetwindow 库查找窗口标题,提取其 left, top, width, height 属性作为裁剪参数。这样能确保只截取指定应用,忽略其他重叠窗口。

import pygetwindow as gw
import mss
# 查找窗口
win = gw.getWindowsWithTitle('记事本')[0]
rect = {'left': win.left, 'top': win.top,
'width': win.width, 'height': win.height}
with mss.mss() as sct:
# 截取指定区域
screenshot = sct.grab(rect)
如何将截取的图像序列转换为GIF
利用 Pillow 的 GifImagePlugin 将多张截图拼接。设置 save_all=True 和 append_images 参数,指定 duration 控制播放速度,调用 save() 写入文件。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

from PIL import Image
import io
frames = []
for _ in range(5): # 模拟5帧
frames.append(Image.frombytes(
'RGB', (screenshot.width, screenshot.height), screenshot.bgra))
frames[0].save(
'output.gif',
save_all=True,
append_images=frames[1:],
duration=100,
loop=0
)如何处理窗口移动导致的坐标偏移
在循环截取前重新查询窗口位置,因为窗口可能移动。每次迭代都更新 rect 字典,确保截取内容始终对应当前可见的窗口区域,避免截到背景或其他应用。

















