Home > Back-end >  Selenium how to save screenshot to specific directory in Python
Selenium how to save screenshot to specific directory in Python

Time:07-29

I would like to take a screenshot for my selenium driver and save it to a specific directory. Right now, I can run:

driver.save_screenshot('1.png')

and it saves the screenshot within the same directory as my python script. However, I would like to save it within a subdirectory of my script. I tried the following for each attempt, I have no idea where the screenshot was saved on my machine:

path = os.path.join(os.getcwd(), 'Screenshots', '1.png')
driver.save_screenshot(path)
driver.save_screenshot('./Screenshots/1.png')
driver.save_screenshot('Screenshots/1.png')

CodePudding user response:

Here's a kinda hacky way, but it ought to work for your end result...

driver.save_screenshot('1.png')

os.system("mv 1.png /directory/you/want/")

You might need to use the absolute path for your file and/or directory in the command above, not 100% sure on that.

CodePudding user response:

You can parse the file path you want to the save_screenshot function.

As your doing this already a good thing to check is that os.getcwd is the same as the location of the script (may be different if your calling it from somewhere else) and that the directory exists, this can be created via os.makedirs.

import os
from os import path

file_dir = path.join(os.getcwd(), "screenshots")
os.makedirs(file_dir, exist_ok=True)

file_path = path.join(file_dir, "screenshot_one.png")
driver.save_screenshot(file_path)

If os.getcwd is not the right location, the following will get the directory of the current script..

from os import path

file_dir = path.dirname(path.realpath(__file__))
  • Related