Rather than writing a script by hand with ImageGrab, we can record the commands that we execute to make a script, called a Macro.
To do this, open the scripts page (shortcut F12) and click on Start in the Macros frame or type F3 or use the command menu Macros/Start. We can then execute actions normally.
The different actions performed are then registered in the macro. When finished, click the Stop (or F4) button in the Macros frame.
Here is an example of a macro recorded with ImageGrab:
We can then edit the resulting script, to remove duplicates or correct certain points. For example in the macro displayed above, you can remove the intermediate DefaultRacine that were generated by entering the root ‘gold’ and keep only the last. Likewise, the JpegCompressionQuality cursor has generated intermediate positions that can be deleted to keep only the last one. Once the script has been rectified, you can restart it (by the Execute button or F5) or save it in a text file (Save button or CTR+S) to reuse it later.
Note that the command to open or close the script page is not recorded in the macro. If necessary, you can add it manually with the script command or the syntax setScript (False) or setScript (True).