Selenium 設置瀏覽器下載 Firefox 和Chrome


當我們在使用Selenium運行自動化測試時,偶爾需要用到下載功能,但瀏覽器的下載可能會彈出下載窗口,或者下載路徑不是我們想要保存的位置,所以在通過Selenium啟動瀏覽器時需要做相關的設置,將使這些設置在啟動的瀏覽器中生效果。

下圖為Firefox的下載彈窗:

 

Firefox 設置瀏覽器下載

 

import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.By; public class FirefoxDown { public static void main(String[] args) { FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("browser.download.folderList", 2); profile.setPreference("browser.download.dir", "d:\\java"); profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "binary/octet-stream"); WebDriver driver =new FirefoxDriver(profile); driver.get("https://pypi.Python.org/pypi/selenium"); driver.findElement(By.partialLinkText("selenium-3.6.0.tar.gz")).click(); } }

 先 new 一個FirefoxProfile()類,通過setPreference 設置瀏覽器下載類型、路徑等。

browser.download.folderList
設置成 0 代表下載到瀏覽器默認下載路徑, 設置成 2 則可以保存到指定目錄。


browser.download.dir
用於指定所下載文件的目錄。 os.getcwd() 函數不需要傳遞參數, 用於返回當前的目錄。


browser.helperApps.neverAsk.saveToDisk
指定要下載頁面的 Content-type 值, “binary/octet-stream” 為文件的類型。下載的文件不同,這里的類型也會有所不一樣。如果不清楚你下載的文件什么類型,請用Fiddler抓包。

 

Chrome 設置瀏覽器下載

 

import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.util.HashMap; public class ChromeDown { public static void main(String[] args) throws InterruptedException { String downloadFilepath = "D:\\java"; 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(); HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>(); options.setExperimentalOption("prefs",chromePrefs); options.addArguments("--test-type"); DesiredCapabilities cap = DesiredCapabilities.chrome(); cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap); cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); cap.setCapability(ChromeOptions.CAPABILITY, options); WebDriver driver = new ChromeDriver(cap); driver.get("https://www.baidu.com"); driver.findElement(By.id("kw")).sendKeys("chrome"); driver.findElement(By.id("su")).click(); Thread.sleep(2000); driver.findElement(By.linkText("普通下載")).click(); } }

相比較Firefox來說,Chrome的下載默認不會彈出下載窗口的,我們主要是想修改默認的默認下載路徑。

Chrome的設置看上去要比Firefox復雜一次,不過,你需要關注兩個設置。

 

profile.default_content_settings.popups  0   設置為禁止彈出下載窗口

download.default_directory    設置為文件下載路徑

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM