Java 如何在使用 chrome 驱动程序/firefox 驱动程序时更改 Webdriver 中的文件下载位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27824124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:06:39  来源:igfitidea点击:

how to change file download location in Webdriver while using chrome driver/firefox driver

javafile-uploadselenium-webdriverdownloadautomated-tests

提问by Shantanu Nandan

I am trying to save an image by using save as option inside a specific folder. I found a way by which I am able to right click on the image which I want to save using save as option. But the problem where I am stuck is after getting the os window which asks where to save the file I am not able to send the desired location because I don't know how to do it. I went through the similar questions asked on this forum but non of them helped so far.

我正在尝试通过在特定文件夹中使用另存为选项来保存图像。我找到了一种方法,可以通过“另存为”选项右键单击要保存的图像。但是我卡住的问题是在获取 os 窗口之后,该窗口询问在哪里保存文件我无法发送所需的位置,因为我不知道该怎么做。我经历了在这个论坛上提出的类似问题,但到目前为止他们都没有帮助。

Code is-

代码是-

For Firefox-

对于 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
   }
 }

This is the pop up window where I am stuck

这是我卡住的弹出窗口

采纳答案by Vivek Singh

There are two things that are going wrong in code.

代码中有两件事出错了。

For Firefox:You need to set

对于 Firefox:您需要设置

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

not to

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

secondly, you are setting preference browser.download.folderlist, it is browser.download.folderList(L caps in folderList).

其次,您正在设置首选项browser.download.folderlist,它是browser.download.folderList(文件夹列表中的大写字母)。

Once you have achieved this both, you can use then your Robot class to perform desired operations.

一旦你实现了这两个,你就可以使用你的 Robot 类来执行所需的操作。

For Chromedriver try out with:

对于 Chromedriver,请尝试:

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

Hope this helps. :)

希望这可以帮助。:)

回答by user1586480

Probably not the best solution but you could try using sikuli api to confirm the save for the box that shows up.

可能不是最好的解决方案,但您可以尝试使用 sikuli api 来确认显示的框的保存。

The save as box is an OS window.

另存为框是一个操作系统窗口。

回答by SiKing

You partially answered your own question:

您部分回答了自己的问题:

the problem where i am stuck is after getting the os window

我被卡住的问题是在获得 os 窗口之后

Selenium is a browserautomation tool - os windowis not a browser! You will need to use something else. There are many choices, depending on your needs: Sikuli, Robot, AutoIt, ...

Selenium 是浏览器自动化工具——os window不是浏览器!您将需要使用其他东西。根据您的需要,有多种选择:Sikuli、Robot、AutoIt、...

回答by Yury Staravoitau

I spent a lot of time to investigate how to download pdf file in firefox browser without Save As popup appearance. It migth be help someone.

我花了很多时间研究如何在没有“另存为”弹出窗口外观的情况下在 Firefox 浏览器中下载 pdf 文件。它可能是帮助某人。

After some local investigation, how to download pdffile in firefox without any Save As popup, I found the minimum required preference in firefox profile:

经过一些本地调查,如何在没有任何另存为弹出窗口的情况下在 firefox 中下载pdf文件,我在 firefox 配置文件中找到了最低要求的首选项:

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

Of course you can add some additional preferences.

当然,您可以添加一些其他首选项。

It works in Firefox 45-46 versions.

它适用于 Firefox 45-46 版本。

回答by Muhammad

For Chrome Browser:

对于Chrome 浏览器

Even you can disable the windows dialogue (Save As Dialogue) with the following code snippet. You need to do following settins in the chromedriver preferences:

即使您可以使用以下代码片段禁用 Windows 对话框(另存为对话框)。您需要在 chromedriver 首选项中执行以下设置:

  • turn off the download prompt if it appears
  • set the default directory to download the file
  • If PDF view plugin is enabled which opens the PDF file in browser, you can disable that so that download can start automatically
  • Accept any certificate in 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);
    
  • 如果出现下载提示,请关闭
  • 设置下载文件的默认目录
  • 如果启用了在浏览器中打开 PDF 文件的 PDF 查看插件,您可以禁用它,以便下载可以自动开始
  • 在浏览器中接受任何证书

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

回答by Thirumaran

Use the same Robot class and press enter to select the "Save" in the Windows dialog box.

使用相同的机器人类并按回车键选择 Windows 对话框中的“保存”。

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

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

if you need to rename it copy the file name in the clipboard and pass like below

如果您需要重命名它,请复制剪贴板中的文件名并按如下方式传递

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

Robot rb = new Robot();

rb.setAutoDelay(2000); // 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);

回答by Bachan Joseph

For Chrome, it will works

对于 Chrome,它会起作用

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);
WebDriver driver = new ChromeDriver(options);