Selenium screenshot

Time:2021-11-1

When the automated test program is running, there are some problemsbugAt this time, we hope to save the screenshot of the currently running screen to facilitate subsequent debugging and repair by developers.

Provided by seleniumScreen capture method

Serial number Method / attribute describe
1 save_screenshot(filename) Capture the current screen shot and save it as the specified file. Filename is the specified save path or picture file name
2 get_screenshot_as_base64() Get current screenshotbase64Encoding string
3 get_screenshot_as_file(filename) Get the current screenshot and use the full path
4 get_screenshot_as_png() Get binary data of current screenshot

Instance operation

#App 1: save_ Screenshot is saved directly in the current path
from selenium import webdriver
from time import sleep

Driver = webdriver. Chrome() # open browser
driver.get(" https://www.baidu.com/ ") # jump to test page
sleep(1)
element = driver.find_ element_ by_ ID ("kW") # positioning input box
element.send_ Keys ("automated test") # input
sleep(1)
driver.save_ Screenshot ("Baidu. PNG") # screenshot
sleep(2)

Driver. Quit() # close browser
#App 1: save_ Screenshot uses the current time as the file name
from selenium import webdriver
from time import sleep, strftime, localtime, time

Driver = webdriver. Chrome() # open browser
driver.get(" https://www.baidu.com/ ") # jump to test page
sleep(1)
element = driver.find_ element_ by_ ID ("kW") # positioning input box
element.send_ Keys ("automated test") # input
sleep(1)
file_name = strftime("%Y%m%d-%H%M%S", localtime(time())) + ".png"
driver.save_ Screenshot (file_name) # screenshot
sleep(2)

Driver. Quit() # close browser