在 Selenium 中訪問 Firefox 中的檔案下載對話方塊。
我們可以在 Selenium 中訪問 Firefox 中的檔案下載對話方塊。為此,我們必須首先修改下載的檔案儲存的預設目錄。這是透過addpreference 方法完成的。
p.addPreference("browser.download.folderList", 2);
然後,定義下載目錄的新路徑。
最後,我們將透過其 MIME 程式碼忽略透過檔案型別的對話方塊中儲存到磁碟和開啟檔案選項。addPreference 方法可在FirefoxOptions 類的幫助下呼叫。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import java.util.concurrent.TimeUnit; public class FileDwnloadWithoutDialg{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); // instance of FirefoxOptions class FirefoxOptions profile = new FirefoxOptions(); // adding browser preferences with addPreference method profile.addPreference("browser.download.folderList", 2); // location of downloaded file profile.addPreference("browser.download.dir", "C:\Users\ghs6kor\Documents\Download"); profile.addPreference("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.addPreference("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"); // connecting browser options to webdriver WebDriver driver = new FirefoxDriver(profile); driver.get("https://the-internet.herokuapp.com/download"); //maximize window driver.manage().window().maximize(); // identify element and start download driver.findElement(By.linkText("xls-sample3.xls")).click(); } }
廣告