Saving Files from a Loop Without Overwrite

天大地大妈咪最大 提交于 2020-01-06 01:32:10

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/30664786/saving-files-from-a-loop-without-overwrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!