做自動化過程中時長會遇到一些截圖操作,那么在做客戶端的時候,應該怎么進行截圖呢?
窗口截圖
在pywinauto中存在自帶的截圖函數 capture_as_image()
源碼:
def capture_as_image(self, rect=None): """ Return a PIL image of the control. See PIL documentation to know what you can do with the resulting image. """ control_rectangle = self.rectangle() if not (control_rectangle.width() and control_rectangle.height()): return None # PIL is optional so check first if not ImageGrab: print("PIL does not seem to be installed. " "PIL is required for capture_as_image") self.actions.log("PIL does not seem to be installed. " "PIL is required for capture_as_image") return None if rect: control_rectangle = rect # get the control rectangle in a way that PIL likes it width = control_rectangle.width() height = control_rectangle.height() left = control_rectangle.left right = control_rectangle.right top = control_rectangle.top bottom = control_rectangle.bottom box = (left, top, right, bottom) # check the number of monitors connected if (sys.platform == 'win32') and (len(win32api.EnumDisplayMonitors()) > 1): hwin = win32gui.GetDesktopWindow() hwindc = win32gui.GetWindowDC(hwin) srcdc = win32ui.CreateDCFromHandle(hwindc) memdc = srcdc.CreateCompatibleDC() bmp = win32ui.CreateBitmap() bmp.CreateCompatibleBitmap(srcdc, width, height) memdc.SelectObject(bmp) memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY) bmpinfo = bmp.GetInfo() bmpstr = bmp.GetBitmapBits(True) pil_img_obj = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1) else: # grab the image and get raw data as a string pil_img_obj = ImageGrab.grab(box) return pil_img_obj
實戰
上面的操作方法已經了解了,我們實戰進行操作,看看進行如何截圖,這里我們截圖后,要進行保存,可以根據路徑保存或者直接保存在當前目錄
# coding:utf-8 from pywinauto import Application # 打開記事本 app = Application().start(r'C:\Windows\System32\notepad.exe') win = app['無標題 - 記事本'] # 截圖進行保存 a = win.capture_as_image().save('123.png')