WebDriver has built-in methods for capturing the screen in a test and saving it.
Sample Script:
(1) save_screenshot(filename): save screenshot
from selenium import webdriver from time import sleep,strftime,localtime,time import os class TestScreenShot(object): def setup(self): = () ("") def test_screen(self): .save_screenshot("") def teardown(self): () if __name__ == '__main__': shot=TestScreenShot() shot.test_screen()
(2) get_screenshot_as_base64(): get current screenshot base64 encoding string
from selenium import webdriver from time import sleep,strftime,localtime,time import os class TestScreenShot(object): def setup(self): = () ("") def test_screen(self): .save_screenshot("") print(.get_screenshot_as_base64()) def teardown(self): () if __name__ == '__main__': shot=TestScreenShot() shot.test_screen()
Run results:
(3) get_screenshot_as_file(filename): get current screenshot, use full path
from selenium import webdriver from time import sleep,strftime,localtime,time import os class TestScreenShot(object): def setup(self): = () ("") def test_screen(self): .get_screenshot_as_file("") def teardown(self): () if __name__ == '__main__': shot=TestScreenShot() shot.test_screen()
(4) get_screenshot_as_file(filename): get the current screenshot, use the full path, the file name is named after the time.
from selenium import webdriver from time import sleep,strftime,localtime,time import os class TestScreenShot(object): def setup(self): = () ("") def test_screen(self): # print(.get_screenshot_as_png()) # .get_screenshot_as_file("") # .save_screenshot("") # print(.get_screenshot_as_base64()) .find_element_by_id("kw").send_keys("selenium test") .find_element_by_id("su").click() str = strftime("%Y-%m-%d-%H-%M-%S",localtime(time())) filename = str + ".png" path =("screenshots") filepath=path + '/'+filename .get_screenshot_as_file(filepath) print(filepath) def teardown(self): () if __name__ == '__main__': shot=TestScreenShot() shot.test_screen()
(5) get_screenshot_as_png(): get the binary file data of the current screenshot
from selenium import webdriver from time import sleep,strftime,localtime,time import os class TestScreenShot(object): def setup(self): = () ("") def test_screen(self): print(.get_screenshot_as_png()) def teardown(self): () if __name__ == '__main__': shot=TestScreenShot() shot.test_screen()
Run results:
Above is the details of python automation test selenium screenshot example, more information about selenium screenshot example, please pay attention to my other related articles!