Downloading PDF using Selenium Java not working in Chrome

随声附和 提交于 2021-01-29 05:41:35

问题


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?


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/55019944/downloading-pdf-using-selenium-java-not-working-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!