pythonspynner

Saving Files from a Loop Without Overwrite


Currently my python script (which uses 'Spynner') has a loop which contains:

browser.load(url)
time.sleep(5)
browser.snapshot().save('example.png')

...but the problem is that every time the loop cycles it overwrites the previously stored image with an image of the newly rendered URL (the URL changes each time the loop is run) instead of making a new image, separate from the previous one. I have created a count but for some reason:

browser.snapshot().save((count)'.png')

doesn't seem to work. How do you use a defined count as part of a filename with .save?

Thanks


Solution

  • browser.snapshot().save('{:03d}.png'.format(count))
    

    should do it. You can change the format operator (:03d) to a bigger number if you need to.

    This will give you files with the format 000.png, 001.png, etc. Just using str(count)+'.png' will not pad the zeroes at the front, making for more difficult file handling later