Selenium firefox profile update download directory after creating webdriver - python

I'm wondering how can I update/change download location in selenium once I started driver?
it is not problem to set download dir during creation of profile and initiation of webdriver. The problem appears after initiation of webdriver to change directory depending on data type.
For example
-if dl doc is word save in Docs\Word
-if dl doc is pdf save in Docs\pdf
this is my code
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.dir', os.getcwd())
profile.set_preference("browser.download.folderList", 2)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/download,application/octet-stream,application/pdf')
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
driver.delete_all_cookies()
sleep(10)
# this part doesn't work
driver.profile.set_preference('browser.download.dir',"{0}\{1}".format(os.getcwd(),"Docs"))
driver.profile.update_preferences()

With Firefox it's possible to change the preferences at run-time with a scrip injection once the context is set to chrome:
def set_download_dir(driver, directory):
driver.command_executor._commands["SET_CONTEXT"] = ("POST", "/session/$sessionId/moz/context")
driver.execute("SET_CONTEXT", {"context": "chrome"})
driver.execute_script("""
Services.prefs.setBoolPref('browser.download.useDownloadDir', true);
Services.prefs.setStringPref('browser.download.dir', arguments[0]);
""", directory)
driver.execute("SET_CONTEXT", {"context": "content"})

Related

How to save Firefox's user profile after using it | Python Selenium Firefox

Previously, I use to load and save cookies which is an inconvenient way for most websites. Instead, I use a User Profile to make it run flawlessly.
The problem is I able to load the User Profile but not save it. After I make some changes to the browser such as config addons, changing themes, logging into some websites, etc., exit Firefox via input('exit?') (see the code below), I reopen Firefox with the same User Profile and notice that nothing was saved to the User Profile (I use both methods, open Firefox and select the User Profile (via cmd "Firefox.exe -P"); rerun the script).
Selenium v3.14.0
Python v3.9.7
GeckoDriver v0.30.0 (64-bit)
Firefox v103.0.1 (64-bit)
import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
FireFoxPath = r"C:\\Program Files\\Mozilla Firefox\\firefox.exe"
DriverPath = r"BrowserDriver\geckodriver-v0.30.0-win64\geckodriver.exe"
FirefoxProfilePath = os.path.join(os.getcwd(), 'Playground_Temp')
# Initialize
options = webdriver.FirefoxOptions()
options.binary_location = FireFoxPath
options.set_preference('app.update.auto', False)
options.set_preference('app.update.enable', False)
capabilities = DesiredCapabilities.FIREFOX
capabilities["pageLoadStrategy"] = "none"
# Start Firefox
driver = webdriver.Firefox(
webdriver.FirefoxProfile(FirefoxProfilePath),
desired_capabilities=capabilities,
options=options,
executable_path=DriverPath
)
# Wait for user make changes
input('exit?')
# Quit Firefox
driver.quit()

Downloading images at a particular location in selenium python

I am trying to download images using selenium but I don't know how to direct those files at a desired location. Can anyone tell me how to do this?
Use this code to set desire download location in Selenium-Python bindings :
executable_path = r"C:\\Selenium+Python\\chromedriver.exe"
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : '/path/to/dir'}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path, options=options)
You need to change /path/to/dir to your desired location.
In case you are using a Chrome webdriver you can use these settings:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("download.default_directory=C:/Downloads")
driver = webdriver.Chrome(chrome_options=options)
Here I set it to "C:/Downloads" but you can change it to any other destination.
For the Firefox you can use this:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", 'PATH TO DESKTOP')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")
driver = webdriver.Firefox(firefox_profile=profile)
Where 'PATH TO DESKTOP' is a path on your disk where you want to download your files
as per this post to download using firefox
from selenium import webdriver
profile = webdriver.FirefoxProfile()
path = 'C:\\downloads'
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', path)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'image/png', 'image/jpeg')
then select the button to download and click it.
if you only have the link of the image, i'd recommend using something like mechanize or urllib to download the contents
img = driver.find_element_by_xpath(xpath)
src = img.get_attribute('src')
# download the image
req = urllib.urlopen(src)
f = open(filename,'wb')
f.write(req.read())
f.close()

How to change the target directory for a screenshot using Selenium webdriver in Firefox or Chrome

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?
You need to consider a couple of facts as follows:
profile.set_preference('key', 'value')
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.
save_screenshot(filename)
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.
Solution
To save the screenshot in a different directory you need to pass the absolute path as follows:
driver.save_screenshot("./my_directory/foo.png")
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
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}

Why is Firefox not using the profile preferences via selenium?

I am trying to download a PDF files using Firefox in Selenium but the preferences I have set below do not seem to be working. Whenever I run the code, I am still getting the "You have chosen to open:" dialog box even though the preferences state that PDF files should automatically be downloaded.
Am I missing something?
def setUp(self):
downloads_folder = initialSearch.download_path(self)
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.dir", downloads_folder)
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")
self.driver = webdriver.Firefox(profile)
Try this one profile.update_preferences() before
webdriver.Firefox(profile)
please may help you

What is wrong with this selenium firefox profile to download file into customized folder?

I am using selenium and python v3.6 to automate firefox to download file into a customized folder. The location of the folder is C:/Users/username/Dropbox/Inv/.
Below is my firefox profile.
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', 'C:/Users/username/Dropbox/Inv/')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/plain')
profile.set_preference('browser.helperApps.neverAsk.openFile', 'text/plain')
Currently, the file is always downloaded in the default folder C:\Users\username\Downloads. How do I get the downloaded folder location to be C:/Users/username/Dropbox/Inv/?
You need to use profile while launching Firefox:
driver = webdriver.Firefox(firefox_profile = profile)
Check 8.4. How to auto save files using custom Firefox profile ? in Selenium Docs FAQ.
This is the example in the link:
import os
from selenium import webdriver
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")
browser = webdriver.Firefox(firefox_profile=fp)
browser.get("http://pypi.python.org/pypi/selenium")
browser.find_element_by_partial_link_text("selenium-2").click()
I will answer my own question. The problem lies with the string specifying the download directory. I should use \\ and not /.
profile.set_preference('browser.download.dir', 'C:\\Users\\username\\Dropbox\\Inv')
The code has been verified to be working now.

Categories

Resources