当咱们在使用Selenium运行自动化测试时,偶尔须要用到下载功能,但浏览器的下载可能会弹出下载窗口,或者下载路径不是咱们想要保存的位置,因此在经过Selenium启动浏览器时须要作相关的设置,将使这些设置在启动的浏览器中生效果。java
下图为Firefox的下载弹窗:chrome
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
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