Saving Files from a Loop Without Overwrite

4.7k Views Asked by At

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

2

There are 2 best solutions below

3
On BEST ANSWER
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

1
On

try this

for counter,url in enumerate(urls):
    browser.load(url)
    time.sleep(5)
    browser.snapshot().save(str(counter) + '.png')

or just set counter = 0, then run the loop, incrementing counter after each save like this : -

counter = 0
for url in urls:
    browser.load(url)
    time.sleep(5)
    browser.snapshot().save(str(counter) + '.png')
    counter += 1