import
win32gui, win32ui, win32con, win32api
def
window_capture(filename):
hwnd
=
0
hwndDC
=
win32gui.GetWindowDC(hwnd)
mfcDC
=
win32ui.CreateDCFromHandle(hwndDC)
saveDC
=
mfcDC.CreateCompatibleDC()
saveBitMap
=
win32ui.CreateBitmap()
MoniterDev
=
win32api.EnumDisplayMonitors(
None
,
None
)
w
=
MoniterDev[
0
][
2
][
2
]
h
=
MoniterDev[
0
][
2
][
3
]
saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
saveDC.SelectObject(saveBitMap)
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)
browser.execute_script(
)
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"
)