近期收到了電子工業出版社贈送的一本網絡安全書籍《python黑帽子》,書中一共24個實驗,今天復現第20個實驗( 截屏),我的測試環境是windows虛擬機+conda開發環境+python3.7。這個實驗非常有趣,在windows環境下,運行腳本就能自動截屏,我這邊測試的時候發現,在虛擬機截屏不完整,可能和分辨率有關系~
1、學生只需要在cmd中運行python腳本,即可產生桌面的截圖
2、可以在運行腳本的目錄下查看屏幕的截圖,這裡截的不全
參考代碼:
# -*- coding: utf-8 -*-
# @Time : 2022/6/25 8:17 AM
# @Author : ailx10
# @File : screenshot.py
import base64
import win32api
import win32con
import win32gui
import win32ui
def get_dimensions():
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
return (width,height,left,top)
def screenshot(name="screenshot"):
hdesktop = win32gui.GetDesktopWindow()
width,height,left,top = get_dimensions()
desktop_dc = win32gui.GetWindowDC(hdesktop)
img_dc = win32ui.CreateDCFromHandle(desktop_dc)
mem_dc = img_dc.CreateCompatibleDC()
screenshot = win32ui.CreateBitmap()
screenshot.CreateCompatibleBitmap(img_dc,width,height)
mem_dc.SelectObject(screenshot)
mem_dc.BitBlt((0,0),(width,height),img_dc,(left,top),win32con.SRCCOPY)
screenshot.SaveBitmapFile(mem_dc,f"{name}.bmp")
mem_dc.DeleteDC()
win32gui.DeleteObject(screenshot.GetHandle())
def run():
screenshot()
with open("screenshot.bmp") as f:
img = f.read()
return img
if __name__ == "__main__":
screenshot()