sprogissd
sprogissd

Reputation: 3075

How to save screenshots with unique files names using Selenium Webdriver with Python?

Is is possible for Selenium Webdriver to create screenshots with unique file names? If I use the standard command browser.save_screenshot(screenshot.png), my Python script overrides the saved screenshot every time it takes a screenshot.

If, however, I do something like the following to create a unique file name and try to parse the string as a function argument, it doesn't work because apparently Python doesn't do that.

from selenium import webdriver
import datetime
browser = webdriver.Firefox()
browser.get("http://www.google.com")
date_stamp = str(datetime.datetime.now()).split('.')[0]
date_stamp = date_stamp.replace(" ","_")
file_name = date_stamp + ".png"
browser.save_screenshot(file_name)

Upvotes: 1

Views: 3029

Answers (2)

Māris L
Māris L

Reputation: 37

from datetime import datetime

@classmethod
def tearDown(cls):
    now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    cls.driver.get_screenshot_as_file('reports/screenshot-%s.png' % now)

I have like this. When test finishes, it generate screenshot with creation time in name

Upvotes: 0

Andersson
Andersson

Reputation: 52665

Your date_stamp returns something like "2017-06-09_20:56:54.png" which is not acceptable file name. Try to use

date_stamp = date_stamp.replace(" ", "_").replace(":", "_").replace("-", "_")

which should return you valid name

"2017_06_09_20_56_54.png"

Upvotes: 2

Related Questions