Downloading PDF using Selenium Java not working in Chrome - java

I have written the following code to disable the Chrome PDF viewer so that the PDF file can be downloaded automatically in the C:\downloads folder when the link is opened in Chrome.
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", "C:\\downloads");
prefs.put("download.prompt_for_download", false);
prefs.put("plugins.always_open_pdf_externally", true);
options.setExperimentalOption("prefs", prefs);
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
Unfortunately the PDF viewer does not get disabled properly I believe. Here's what I get with this code when I open that PDF url:
Even if I enable the Download PDF files instead of automatically opening them in Chrome, I still get the above result.
Is there any other solution to get the file downloaded automatically in Chrome?

I managed automatic PDF download in Chrome with loading existing browser profile. Maybe you need just a profile without PDF viewer.
public class WebdriverSetup {
public static String chromedriverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe";
public static String chromeProfilePath = "C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data";
public static WebDriver driver;
public static WebDriver startChromeWithCustomProfile() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=" + chromeProfilePath);
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
public static void shutdownChrome() {
driver.close();
driver.quit();
}
}

Related

Unable to run the test scripts using Chrome Driver though am able to hit the browser with Driver.get("url")

My below code is giving expected result to hit chrome browser with the url and maximize the window.But after that it should go my my test scripts where is have login page and it is doing nothing over there
Please suggest
#BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\NCRExecutableWorkSpace\\automation-ncr\\Drivers\\chromedriver.exe");
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", map);
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get("https://google.com");

How to download a file from a website in a specific folder, I am using Chorme

I'm trying to download a file from a website that has to be saved in a specific folder. Website http://bookboon.com/en/basics-of-accounting-information-processing-ebook
When I click on download it saves the file in the download section, I also tried to change the download directory in chrome settings, it doesn't work. I am trying automation (selenium, java). Is there any way?
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User_2\\Downloads\\chromedriver_win32\\chromedriver.exe");
d = new ChromeDriver();
d.get("http://bookboon.com/en/basics-of-accounting-information-processing-ebook");
d.findElement(By.id("email")).sendKeys("asd#ymail.com");
WebElement One=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[1]/input"));
One.sendKeys("Studying");
One.sendKeys(Keys.TAB);
WebElement Two=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[2]/input"));
Two.sendKeys("Engineer/Science MSc");
Two.sendKeys(Keys.TAB);
WebElement Three=d.findElement(By.xpath("html/body/div[1]/div/article/div/section[1]/form/div[2]/div[2]/div[3]/input"));
Three.sendKeys("All India Institute of Medical Sciences (AIIMS), Delhi");
Three.sendKeys(Keys.TAB);
d.navigate().back();
downlinks = d.findElements(By.className("pdf"));
}
}
For Chromedriver It will work
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);
For Firefox: You need to setPreference
profile.setPreference("browser.download.dir", "Filepath");
Hope this helps. :)

How to TakeScreenshots Selenium ChromeOption Driver

Not able to capture screen shots for electron application using java .
Here is my code for webdriver setup.
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary("/Applications/betlite.app/Contents/MacOS/appname");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new ChromeDriver(capabilities);
Using following method to capture screen , it do work for traditional ChromeDriver .
public static void captureScreenMethod() throws IOException, InterruptedException
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
Thread.sleep(4000);
FileUtils.copyFile(scrFile, new File("path_of_file/screenshot.png"));
}
I am getting following error -
org.openqa.selenium.WebDriverException: unknown error: cannot get
automation extension from unknown error: page could not be found:
chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
I am using MAC OS
Thanks

How to Avoid Window Download Popup in Firefox use Java selenium? i need download automatically with out ask popup?

My code is here:-
WebDriver driver = new FirefoxDriver();
driver.get("http://www.sample-videos.com/");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='sample-mp4-video']/table/tbody/tr[0]/td[4]")).click();
Objective is to handle windows popup so that the download file is saved to local drive.
Is there any way to automate using selenium
You can automatically download a file by customising the preferences. You need to define the download folder in browser.download.dir and the MIME type of the file that will be downloaded (video/mp4 in your example). Note that the MIME type is the Content-Type header returned in the response of the request.
Here is a working example with the page from your post:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir", "C:\\Temp"); // folder
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "video/mp4"); // MIME type
profile.setPreference("pdfjs.disabled", true); // disable the built-in viewer
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.panel.shown", false);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
capabilities.setCapability(CapabilityType.ELEMENT_SCROLL_BEHAVIOR, 1);
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("http://www.sample-videos.com/");
// click on the link "10 mp4 720x480"
driver.findElement(By.xpath("//tr[td='10'][td='mp4'][td='720x480']//a")).click();
You need use Firefox profiling to overcome from this issue:-
FirefoxProfile pro=new FirefoxProfile();
pro.setPreference("browser.downLoad.folderList", 0);
pro.setPreference("browser.helperApps.neverAsk.saveToDisk", "Applications/zip");
WebDriver driver=new FirefoxDriver(pro);
browser.download.folderList controls the default folder to download a file to. 0 indicates the Desktop; 1 indicates the systems default downloads location; 2 indicates a custom folder.
browser.download.dir holds the custom destination folder for
downloading. It is activated if browser.download.folderList has been set to 2.
browser.helperApps.neverAsk.saveToDisk stores a comma-separated list of MIME types to save to disk without asking what to use to open the file.
Below code for chrome multiple download option:-
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings.popups", 0);
prefs.put("download.default_directory", getClass().getResource("/data/input").toString().replace("%20", " ").replace("file:","").replaceFirst("/", ""));
options.setExperimentalOption("prefs", prefs);
options.addArguments("--test-type");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
For IE Refer :-
http://9to5it.com/internet-explorer-disable-do-you-want-to-open-or-save-this-file-prompt/
You can also use Robot class of java but it can lock your screen for while
You need to use ROBOT class for firing an ENTER Action event. In java if you want to fire any event you have to use Robot class for typing using programatically or firing events like ENTER and ESCAPE.
// Create object of Robot class
Robot object=new Robot();
// Press Enter
object.keyPress(KeyEvent.VK_ENTER);
// Release Enter
object.keyRelease(KeyEvent.VK_ENTER);
Hope it will help you :)
Please get back to me if still facing issue :)
Use this code and try. It will download automaticallly.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.sample-videos.com/");
driver.manage().window().maximize();
Thread.sleep(5000L);
driver.findElement(By.xpath(".//*[#id='sample-mp4-video']/table/tbody/tr[1]/td[4]/a")).click();
Thread.sleep(5000L);
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Reply to me for further query.
Happy learning. Enjoy :-)
I got this resolved by using the below code snippet
System.setProperty(GEKO_DRIVER, FIREFOX_DRIVER_LOCATION);
FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.helperApps.neverAsk.openFile",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.closeWhenDone", false);
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
You can do it using a Firefox profile:
public class FileDownloadExample
{
public static String downloadPath = "D:\\seleniumdownloads";
#Test
public void testDownload() throws Exception
{
WebDriver driver = new FirefoxDriver(FirefoxDriverProfile());
driver.manage().window().maximize();
driver.get("http://URL");
driver.findElement(By.linkText("test.xls")).click();
}
public static FirefoxProfile FirefoxDriverProfile() throws Exception
{
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.dir", downloadPath);
profile.setPreference("browser.helperApps.neverAsk.openFile",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.closeWhenDone", false);
return profile;
}
}

Selenium Automation a new window handle

So after my code runs a new window shows up to download a CSV. A window pops up to either save the file or to open it with excel. How would I change windows to download that csv to a path using selenium.
public class automation {
public static void main(String[] args) {
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\\Users\\K344975\\Desktop";
profile.setPreference("browser.download.dir",path);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/xls;text/csv");
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;application/xls;");
WebDriver driver = new FirefoxDriver(profile);
driver.get("");
String winHandle = driver.getWindowHandle();
System.out.println(winHandle);
//driver.quit();
}
}
I also tried making a profile
Well you have firstly patch profile and only after it create browser, and for plugin disable you could use
profile.setPreference("plugin.disable_full_page_plugin_for_types",
"application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;")

Categories