Search code examples
pythoncoordinatesscreenshotregionpyautogui

can locateCenterOnScreen coordinates be passed to the X Y parameter to screenshot a region with Python?


New to python (within the past couple months) and I'm enjoying it. It is easy to understand and to use. Except in this case!

I wrote a script that works for logging into a site with selenium, navigating to a particular page, entering date values and showing the results I need. It scrolls into position, then I need to screenshot just a portion of that page. At first I would just have it save the whole screen and I would crop it later, but I believe it is possible (and more efficient) to only screenshot the area I need.

I have tried multiple methods of locating where the corner would start and selecting the region, and ultimately decided to go with pyautogui using locateCenterOnScreen of a sample screenshot of just the spot I want, where the center marks the upper-left corner of the entire part I want to save. This ensures that if the window is not in the same place every time, it will accurately save the correct region no matter where it is.

Thus, using

location = pyautogui.locateCenterOnScreen('ctr_cornerScreenshot.PNG')

returns a correct (X, Y) value to properly locate the coordinates for the screenshot. Then, I'm using

screengrabPic = pyautogui.screenshot(region=(location, 720, 340)) screengrabPic.save("transactions.png")

the error turns out as

AssertionError: region argument must be a tuple of four ints

I'm sure because of the region parameter passed in as location, and I've tried (int(location) or 'locationX, locationY,

I figured I'd reach out for help rather than spin my wheels too much more. Thanks!


Solution

  • OK, so I did a lot more trial and error then found the final solution.

    location = pyautogui.locateCenterOnScreen('ctr_cornerScreenshot.PNG')
    print(location)
    locationX, locationY = pyautogui.locateCenterOnScreen('ctr_cornerScreenshot.PNG')
    screengrabPic = pyautogui.screenshot(region=(locationX, locationY, 720, 340))
    screengrabPic.save("tolls_" + filename + ".png")
    

    On pyautogui.readthedocs it explains this syntax, yet it wasn't specific that the requirement was to run locate center once first, then again for locationX and locationY.