相关文章推荐
忐忑的眼镜  ·  jquery 绑定事件 - blur() ...·  1 年前    · 
千年单身的蚂蚁  ·  【Spring ...·  1 年前    · 
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)
beg = time.time()
for i in range ( 10 ):
window_capture( "haha.jpg" )
end = time.time()
print (end - beg)
debug = False
for i in range ( 10 ):
img = ImageGrab.grab(bbox = ( 250 , 161 , 1141 , 610 ))
img = np.array(img.getdata(), np.uint8).reshape(img.size[ 1 ], img.size[ 0 ], 3 )
end = time.time()
print (end - beg)

输出结果为4.015秒,也就是说截取一次屏幕需要半秒钟,更何况此处只截取了窗口的一部分矩形区域。所以ImageGrab模块能用是能用,就是有点慢。

三、使用Selenium截图

使用Selenium只能进行WEB程序截图

使用Selenium的各个浏览器需要制定驱动的位置,驱动下载地址参见Selenium 官网

from selenium import webdriver
import time
def capture(url, filename = "capture.png" ):
browser = webdriver.Chrome(r "C:\Users\weidiao\Desktop\chromedriver_win32\chromedriver.exe" )
browser.set_window_size( 1200 , 900 )
browser.get(url) # Load page
browser.execute_script( """
(function () {
var y = 0;
var step = 100;
window.scroll(0, 0);
function f() {
if (y < document.body.scrollHeight) {
y += step;
window.scroll(0, y);
setTimeout(f, 50);
} else {
window.scroll(0, 0);
document.title += "scroll-done";
setTimeout(f, 1000);
})();
""" )
for i in range ( 30 ):
if "scroll-done" in browser.title:
break
time.sleep( 1 )
beg = time.time()
for i in range ( 10 ):
browser.save_screenshot(filename)
end = time.time()
print (end - beg)
browser.close()
capture( "//www.jb51.net" )