Changing the file download location in Webdriver when utilizing either the Chrome driver or Firefox driver

I'm currently facing an issue with saving an image in a specific folder using the "save as" option. I've figured out how to right click on the image and select the "save as" option, but I'm struggling when it comes to choosing the desired location in the operating system window that pops up. I've searched through similar questions on this forum, but none of the solutions have worked for me so far.

Here is the code snippet:

For Firefox-

public class practice {

 public void pic() throws AWTException{
     WebDriver driver;

     //Proxy Setting     
        FirefoxProfile profile = new FirefoxProfile();
        profile.setAssumeUntrustedCertificateIssuer(false);
        profile.setEnableNativeEvents(false);
        profile.setPreference("network.proxy.type", 1);
        profile.setPreference("network.proxy.http", "localHost");
        profile.setPreference("newtwork.proxy.http_port",3128);

        //Download setting
        profile.setPreference("browser.download.folderlist", 2);
        profile.setPreference("browser.helperapps.neverAsk.saveToDisk","jpeg");
        profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");
        driver = new FirefoxDriver(profile);

        driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
        driver.findElement(By.xpath("//*[@id='large-user-info']/div[1]/div[1]/a/div/img"));
        Actions action = new Actions(driver);
        action.moveToElement(driver.findElement(By.xpath("//*[@id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
        action.contextClick().perform();
        Robot robo = new Robot();
        robo.keyPress(KeyEvent.VK_V);
        robo.keyRelease(KeyEvent.VK_V);
    // Here I am getting the os window but don't know how to send the desired location
    }//method   
}//class

For chrome-

public class practice {
   public void s() throws AWTException{
        WebDriver driver;   
        System.setProperty("webdriver.chrome.driver","C:\\Users\\Admin\\Desktop\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.navigate().to("http://stackoverflow.com/users/2675355/shantanu");
        driver.findElement(By.xpath("//*[@id='large-user-info']/div[1]/div[1]/a/div/img"));
        Actions action = new Actions(driver);
        action.moveToElement(driver.findElement(By.xpath("//*[@id='large-user-info']/div[1]/div[1]/a/div/img"))).perform();
        action.contextClick().perform();
        Robot robo = new Robot();
        robo.keyPress(KeyEvent.VK_V);
        robo.keyRelease(KeyEvent.VK_V);
        // Here I am getting the os window but don't know how to send the desired location
   }
 }

Answer №1

In the code, there are two issues that need to be addressed.

For optimal performance in Firefox: Make sure to set

profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\");

instead of

profile.setPreference("browser.download.dir", "C:\\Users\\Admin\\Desktop\\ScreenShot\\pic.jpeg");

Additionally, ensure that you use browser.download.folderList with a capitalized "L" instead of browser.download.folderlist.

Once both of these corrections have been made, you can utilize the Robot class for the necessary actions.

If using Chromedriver, consider implementing the following:

String downloadFilepath = "/path/to/download";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(cap);

I trust this information will be beneficial to you. :)

Answer №2

For Chrome Browser:

You have the ability to prevent the windows dialogue (Save As Dialogue) from appearing by using the code snippet below. Make sure to adjust these settings in your chromedriver preferences:

  • Disable the download prompt if it shows up
  • Specify the default directory for file downloads
  • If the PDF view plugin is activated and opens PDF files in the browser, you can deactivate it to enable automatic downloads
  • Accept any certificates in the browser

    String downloadFilepath = "/path/to/download/directory/";
    Map<String, Object> preferences = new Hashtable<String, Object>();
    preferences.put("profile.default_content_settings.popups", 0);
    preferences.put("download.prompt_for_download", "false");
    preferences.put("download.default_directory", downloadFilepath);
    
    // Disable flash and the PDF viewer
    preferences.put("plugins.plugins_disabled", new String[]{
        "Adobe Flash Player", "Chrome PDF Viewer"});
    
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", preferences);
    
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(capabilities);
    

Answer №3

My recent research led me to discover a way to successfully download PDF files in Firefox without encountering the bothersome Save As popup. This information may prove useful to others.

During my investigation, I uncovered the necessary preference settings in Firefox to enable smooth downloading of PDF files without any interruption:

profile.setPreference("pdfjs.disabled", true);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");

It is possible to include additional preferences as needed.

This method has been tested and confirmed to work on Firefox versions 45-46.

Answer №4

It seems like you've made progress in solving your own question:

I'm facing a challenge once I reach the operating system window

Selenium is primarily designed for automating tasks within web browsers, and an OS window does not fall under that category! You may need to explore other automation tools such as Sikuli, Robot, or AutoIt depending on your specific requirements.

Answer №5

To choose the "Save" option in a Windows dialog box, utilize the Robot class and hit enter.

robo.keyPress(KeyEvent.VK_ENTER); robo.keyRelease(KeyEvent.VK_ENTER);

If you wish to rename it, copy the file name to the clipboard and use the following method:

StringSelection file = new StringSelection("D:\\picture.jpg");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(file, null);

Robot rb = new Robot();

rb.setAutoDelay(2000); // This is similar to thread.sleep

rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);

rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);

rb.setAutoDelay(2000);

rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);

Answer №6

While it may not be the ideal choice, one alternative could be utilizing the sikuli API to validate and confirm the save action for the pop-up box.

It's worth noting that the save as box functions as an operating system window.

Answer №7

For Chrome browser, you can use the following code to set up a download filepath:

String downloadFilepath = "/path/to/downloads";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(options);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues encountered when trying to refresh a form using HtmlUnit in combination with Ajax

Trying to complete and submit an HTML form using HtmlUnit, encountering issues with retrieving a select element loaded via <body onLoad="...">. The Issue: Unable to access the desired select element through methods like getSelectByName or getChildEl ...

Having difficulty extracting table data with selenium and beautiful soup

I've hit a wall in trying to extract data from a table on Yahoo's daily fantasy webpage. Despite scouring StackOverflow for solutions, I can't seem to get the desired information. The table either appears empty or the elements within it are ...

"Dynamically populate dropdown options based on the selection made in another dropdown menu

On a JSP page, I have two dropdown fields and a type4 connection with Oracle 10g. I want the second dropdown to be automatically filled based on the selection from the first dropdown by fetching data from the database. This should happen without refreshing ...

What is the way to determine the length of a list in a velocity template?

Is there a way to determine the size of a list in a velocity template? I am currently working with version 1.4 of Velocity. List<String> list = new ArrayList<String>(); ...

Finding elements based on their class can be accomplished by using XPath

Can you show me how to effectively utilize the :not selector to choose elements in a scenario like this: <div class="parent"> <div class="a b c"/> <div class="a"/> </div> I am trying to select the div with only the class & ...

Is there a way to confirm the alignment of dropdown selections with the user interface choices in Selenium WebDriver with Java?

I've managed to create code that reads options from a property file, but I'm unsure how to verify if the same value exists in the UI drop-down. If anyone could assist me with this code: @Test() public void Filterselection_1() throws Exception{ ...

What is the most effective way to gauge the extent of automation coverage on a system being tested through analytical reports

What are some effective methods for quantifying automation statistics and coverage for a system being tested based on your experience? Summary: Presently, there are more than 100 tests (in feature files & scenarios) categorized by the area of the system ...

What is the best way to implement a jQuery post for a file upload form?

My form has the following structure: <form id="uploadForm" name="uploadForm" method="post" enctype="multipart/form-data"> <input type="file" id="uploadFile" name="uploadFile" /><br /> <input type="submit" id="process" name="pr ...

`Disappointing Outcome: Spring MVC - Ajax file upload fails to function`

I'm having trouble dynamically uploading a file using AJAX and Spring MVC. Here is the approach I am taking: JavaScript function: function initializeQwacCertificate(){ $('#qwac').on('change', function(){ var formData = n ...

Learn how to allow users to download a folder and all of its contents, including subfolders, without compressing the files, directly in

Can you download a folder in its original state without compression through a browser? This means keeping the subfolders and files intact, rather than combining them into a single file. ...

The objects fail to initialize when using PageFactory.initElements(driver,class);

I am facing an issue while trying to initialize objects of the Homepage class Everything was working fine until yesterday, but for some unknown reason today it's not functioning properly package StepDefnitions; import org.openqa.selenium.WebDri ...

How can the driver effectively pause until a specific condition becomes true before resuming if it remains false?

I am currently in the process of automating a workflow that involves generating a report. Each time the report is generated, it takes a varying amount of time (for example, anywhere from 10 to 50 seconds). I am facing difficulty in finding an effective way ...

Dividing an ArrayList of strings into various subparts and storing them in a HashMap: programming in Java with the help of Selenium

Here is a breakdown of the passenger list: 1: Adult(s) ‎(1 X 9,288)‎ 2: Child(s) ‎(1 X 9,288)‎ 3: Infant(s) ‎(1 X 2,429)‎ 4: Adult(s) ‎(1 X2,712)‎ 5: Child(s) ‎(1 X 2,712)‎ 6: Infant(s) ‎(1 X 146) I am trying to extract i ...

Unable to establish a secure connection with Firefox within a 60-second timeframe

Just starting out with Selenium Webdriver and trying to set up the basics. I'm using Windows 7, with Ruby 2.1.5, Selenium-WebDriver 2.45.0, and currently Firefox 33. (After encountering issues with Firefox 37, 36, and 35, I found a solution in a Stack ...

Choosing the appropriate right-click action from the contextual menu in Selenium

I am facing a situation where I need to perform a right click on a link and select the option "Open link in incognito window" from the context menu. However, when I try to do this with the code snippet below, the link ends up opening in the same window ins ...

Troubleshooting Extent Report Issues in Parallel Testing

Here is the Reporting code I am working with: public class Reporting { private ExtentHtmlReporter extentHtmlReporter; private static ThreadLocal<ExtentReports> extentReports = new ThreadLocal<>(); private static ThreadLocal<Ext ...

Utilize.send_keys(Keys.ENTER) for triggering an action in Python

Hey there, I'm a bit lost on where to post this, but I really need some guidance on how to make my code trigger the "ENTER" key using a keyboard input. from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdrive ...

Tips for organizing JSON data based on personal specifications

Currently, I have a list that I am converting into a JSON String object and sending it to the UI. Gson gson = new Gson(); String jsonString = gson.toJson(environmentnamesList); return jsonString; This is the JSON object: [{"id":3272,"company_n ...

Creating a spinning Cube with separate fields for x, y, and z rotation speeds: a step-by-step guide

After dabbling in Java, Visual Basic, HTML, and CSS, I'm now looking to create an interface featuring a central spinning cube with 3 fields to control its x, y, and z rotation speeds. Can you suggest which language would be the best fit for this proje ...

Leverage Multer in NodeJs to efficiently parse files and selectively trigger storage operations

I am utilizing the NextJS endpoint to receive formData with file/files. In order to determine the file name in the Multer storage, I need to parse the file's data and utilize its metadata. For instance, I aim to create an entry in the database for U ...