在用pyautogui模块时,主要功能是根据给定图片,找到屏幕中对应图片,然后执行操作,但是发现pyautogui界面好像处理不了弹窗,一直报错,所以想问下大神们有没有什么好的解决办法。
报错函数是:location=pyautogui.locateCenterOnScreen(img,confidence=0.9),win10,python3.8
报错信息有:
File "D:\software\python\lib\site-packages\pyscreeze_init_.py", line 144, in wrapper
return wrappedFunction(*args, **kwargs)
File "D:\software\python\lib\site-packages\pyscreeze_init_.py", line 456, in _screenshot_win32
im = ImageGrab.grab()
File "D:\software\python\lib\site-packages\PIL\ImageGrab.py", line 44, in grab
include_layered_windows, all_screens
OSError: screen grab failed
这个问题可能是因为 PIL
库在处理窗口时遇到了一些问题,无法抓取屏幕图像。
你可以尝试以下解决方法:
PIL
和 pyautogui
库:pip install --upgrade Pillow
pip install --upgrade pyautogui
win32api
库代替 PIL
进行屏幕截图:import win32gui, win32ui, win32con, win32api
def grab_screen(region=None):
hwin = win32gui.GetDesktopWindow()
if region:
left,top,x2,y2 = region
width = x2 - left + 1
height = y2 - top + 1
else:
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
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)
im = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1)
win32gui.DeleteObject(bmp.GetHandle())
memdc.DeleteDC()
srcdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)
return im
然后你可以使用这个新的 grab_screen
函数来替代 pyautogui.locateCenterOnScreen
。
mss
库:from mss import mss
def grab_screen(region=None):
with mss() as sct:
if region:
return sct.grab(region)
else:
return sct.grab(sct.monitors[0])
以上三种方法都是尝试通过不同方式进行屏幕截图,以避免 PIL
的屏幕抓取失败问题,希望能够对你有所帮助。