Selenium 設置瀏覽器下載 Firefox 和Chrome

當咱們在使用Selenium運行自動化測試時,偶爾須要用到下載功能,但瀏覽器的下載可能會彈出下載窗口,或者下載路徑不是咱們想要保存的位置,因此在經過Selenium啓動瀏覽器時須要作相關的設置,將使這些設置在啓動的瀏覽器中生效果。java

下圖爲Firefox的下載彈窗:chrome

 

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抓包。spa

 

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的下載默認不會彈出下載窗口的,咱們主要是想修改默認的默認下載路徑。firefox

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

 

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

download.default_directory    設置爲文件下載路徑rem

相關文章
相關標籤/搜索