自學Selenium2 ( WebDriver ),理論和實踐的差距還是很大的,所以學習任何編程語言、工具,實踐是最好的老師。 進入正題,這篇文章講述,在自動化測試時,對Firefox瀏覽器的profile設置、啟動有所不同,需根據(jù)自己情況進行相應修改。 1 Firefox的profie設置自動化測試時,有可能會遇到下載文件的情況,如下圖;目前Selenium2還無法處理這樣的對話框,但可通過對Firefox的profile預先進行設置達到自動下載的效果。 1.1 創(chuàng)建FirefoxProfile對象 FirefoxProfile profile = new FirefoxProfile();
1.2 設置下載路徑 // 設置是否詢問下載位置(可忽略);默認true——不詢問,直接下載到指定路徑,具體設置見browser.folderList,false——詢問 profile.setPreference("browser.download.useDownloadDir",true); // 指定下載位置 profile.setPreference("browser.download.downloadDir", "c:\\OutputFolder"); // 設置下載方式;0——下載到桌面,默認1——下載到Firefox默認位置,2——下載到指定位置 profile.setPreference("browser.download.folderList", 2); // 當一個下載開始時,設置是否顯示下載管理器;默認true——顯示,flase——不顯示 profile.setPreference("browser.download.manager.showWhenStarting",false);
2 設置無需確認即可下載的文件格式profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, application/vnd.ms-excel, text/csv, application/zip,application/xml");
注意: MIME類型是設置某種拓展名的文件用一種應用程序打開的方式類型。 常見文件的MIME類型:
有時,需要的文件無法在搜索引擎上查詢到其對應文件類型的MIME類型,可在瀏覽器中查看,如Firefox瀏覽器的工具欄 -> 選項 -> 應用程序。 3 啟動Firefox時加載插件WebDriver啟動的是一個干凈的沒有任務、插件、cookies信息的Firefox瀏覽器(即使本機Firefox安裝某些插件),但在自動化測試中可能需要插件(如Firebug)進行調試。 注意:需要下載firebug.xpi,且最好使用非Firefox瀏覽器下載,不然提示直接安裝到Firefox;最好不要在Firebug官網(wǎng)中下載,因為提示你需要使用Firefox瀏覽器。 // 定義插件所在位置 File file = new File("E:\\Firefox\\files\\firebug-2.0.17.xpi"); // 創(chuàng)建一個FirefoxProfile對象profile FirefoxProfile profile = new FirefoxProfile(); try{ // 將Firebug加載到profile對象中 profile.addExtension(file); }catch (IOException e){ e.printStackTrace(); } // 設置Firebug的當前版本號 profile.setPreference("extensions.firebug.currentVersion","2.0.17"); // 激活Firebug profile.setPreference("extensions.firebug.allPagesActivation","on"); 4 啟動Firefox瀏覽器4.1 Firefox安裝在默認路徑下 直接創(chuàng)建一個FirefoxDriver對象。 WebDriver driver = new FirefoxDriver();
4.2 Firefox未安裝在默認路徑下 需要指定Firefox的可執(zhí)行程序firefox.exe的路徑,再創(chuàng)建FirefoxDriver對象。 System.setProperty("webdriver.firefox.bin", "E:\\Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver(); 結合起來,就是如下代碼: File file = new File("E:\\Firefox\\files\\firebug-2.0.17.xpi"); FirefoxProfile profile = new FirefoxProfile(); try{ profile.addExtension(file); } catch (IOException e){ e.printStackTrace(); } profile.setPreference("extensions.firebug.currentVersion","2.0.17"); profile.setPreference("extensions.firebug.allPagesActivation","on"); profile.setPreference("browser.download.downloadDir","C:\\Output"); profile.setPreference("browser.download.folderList",2); profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, application/vnd.ms-excel, text/csv, application/zip,application/xml"); System.setPreperty("webdriver.firefox.bin","E:\\Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver();
|
|