Reputation: 3387
I want to make a screenshot of a webpage and save it in a custom location using Selenium webdriver with Python. I tried saving the screenshot to a custom location using both Firefox and Chrome but it always saves the screenshot in the project dir. Here is my Firefox version:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.dir",
'C:\\Users\\User\\WebstormProjects')
binary = FirefoxBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
def foxScreen():
driver = webdriver.Firefox(firefox_binary=binary,
firefox_profile=profile)
driver.get("http://google.com")
driver.save_screenshot("foxScreen.png")
driver.quit()
if __name__ == '__main__':
foxScreen()
And here is my Chrome version:
from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": r'C:\\Users\\User\\WebstormProjects',
"directory_upgrade": True}
options.add_experimental_option("prefs", prefs)
chromedriver =
"C:\\Users\\User\\Downloads\\chromedriver_win32\\chromedriver.exe"
def chromeScreen():
driver = webdriver.Chrome(chrome_options=options,
executable_path=chromedriver)
driver.get("http://google.com")
driver.save_screenshot("chromeScreen.png")
driver.quit()
if __name__ == '__main__':
chromeScreen()
I have tried different notations for the location I want the screenshot saved to but that does not seem to help. What should I change so it does not save the screenshot to the project directory but to a given custom location?
Upvotes: 5
Views: 8487
Reputation: 193088
You need to consider a couple of facts as follows:
set_preference(key, value)
sets the preference that we want in the firefox_profile
. This preference is in effect when a specific Firefox Profile is invoked.
As per the documentation save_screenshot(filename)
saves a screenshot of the current window to a PNG image file. This method returns False if there is any IOError, else returns True. Use full paths in your filename.
Args
:
filename: The full path you wish to save your screenshot to. This should end with a .png extension.
Usage
:
driver.save_screenshot(‘/Screenshots/foo.png’)
So, save_screenshot(filename)
expects the full path you wish to save your screenshot to. As you were using:
driver.save_screenshot("foxScreen.png")
Hence the screenshot was always saved within the project directory.
To save the screenshot in a different directory you need to pass the absolute path as follows:
driver.save_screenshot("./my_directory/foo.png")
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
Upvotes: 5
Reputation: 165
Could try adding a few more options. This worked for me:
prefs = {"download.default_directory": r"\download\directory",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True}
Upvotes: 1