本文介绍python如何进行截图保存的几种方法,在测试过程中,是有必要截图,特别是遇到错误的时候进行截图。结合Python其它模块如time ,os.path,基本能满足截图保存文件的功能需求
get_screenshot_as_file()
相关代码如下:
# coding=utf-8
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(6)
driver.get("https://www.baidu.com")
time.sleep(1)
driver.get_screenshot_as_file("C:\\baidu.png")
driver.quit()
代码如下:
import time
from PIL import ImageGrab
if __name__=="__main__":
pic = ImageGrab.grab()
pic.save("picture.jpg")
代码如下:
#coding=utf-8
import time
import win32gui, win32ui, win32con, win32api
def window_capture(filename):
hwnd = 0 # 窗口的编号,0号表示当前活跃窗口
# 根据窗口句柄获取窗口的设备上下文DC(Divice Context)
hwndDC = win32gui.GetWindowDC(hwnd)
# 根据窗口的DC获取mfcDC
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
# mfcDC创建可兼容的DC
saveDC = mfcDC.CreateCompatibleDC()
# 创建bigmap准备保存图片
saveBitMap = win32ui.CreateBitmap()
# 获取监控器信息
MoniterDev = win32api.EnumDisplayMonitors(None, None)
w = MoniterDev[0][2][2]
h = MoniterDev[0][2][3]
# print w,h #图片大小
# 为bitmap开辟空间
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
# 高度saveDC,将截图保存到saveBitmap中
saveDC.SelectObject(saveBitMap)
# 截取从左上角(0,0)长宽为(w,h)的图片
saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
saveBitMap.SaveBitmapFile(saveDC, filename)
if __name__=="__main__":
beg = time.time()
for i in range(1):
image_name="haha%s.jpg"%i
window_capture(image_name)
end = time.time()
print(end - beg)