How to download a file using Selenium?
The below code that we are about to see will download a file from internet. Now without wasting much time, let's look at the code.
In the below example, I'm going to download a Jar file called ojdbc from java2s website and with this we will see, how to simply download the file, but in the homework section for this, I will make it a bit complicated.
package seleniumBasics;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DownloadFile {
public static void main(String[] args) {
try{
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Elcot\\Desktop\\drivers\\gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.java2s.com/Code/Jar/o/Downloadojdbc14jar.htm");
WebElement downloadLink = driver.findElement(By.xpath("/html/body/div/div/div[2]/a"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", downloadLink);
Thread.sleep(2000);
downloadLink.click();
}
catch(Exception e){
e.printStackTrace();
}
}
}
When running the above mentioned code, I got the below output in the browser.

As you can see, my program got terminated when the pop up asking for open or Save File. Find out how to solve this programatically. You can do Save in one program and open with in another program. Consider this as your Homework 3.
One tip, You can use Robot class or Firefox profile to solve this . Search them in Google and find out the solution.