我使用此代码下载文件,但无法正常工作
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir","D:\\WebDriverDownloads");
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
profile.setPreference( "browser.download.manager.showWhenStarting",false );
profile.setPreference( "pdfjs.disabled",true );
FirefoxDriver driver = new FirefoxDriver(profile); //Shows error on this line
driver.get("http://toolsqa.com/automation-practice-form/");
driver.findElement(By.linkText("Test File to Download")).click();
Thread.sleep(5000);
这给了我错误
当我删除
“个人资料”
形成此FirefoxDriver driver = new FirefoxDriver(profile);
然后代码成功运行,但“下载文件”窗口没有关闭,文件也没有下载。
我代替机器人
Robot object=new Robot();
object.keyPress(KeyEvent.VK_DOWN);
object.keyRelease(KeyEvent.VK_DOWN);
object.keyPress(KeyEvent.VK_ENTER);
object.keyRelease(KeyEvent.VK_ENTER);
及其正常工作。但是为什么我上面的代码不起作用?
答案 0 :(得分:1)
要下载文件,请点击链接,其文本为要下载的测试文件,您需要:
您可以使用以下解决方案:
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.dir", "C:\\Utility\\Downloads");
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.helperApps.neverAsk.openFile","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.helperApps.neverAsk.openFile", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
WebDriver driver = new FirefoxDriver(options);
driver.get("http://toolsqa.com/automation-practice-form/");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Test File to Download"))).click();