Selenium 设置浏览器下载 Firefox 和Chrome

时间:2023-03-08 21:40:41

当我们在使用Selenium运行自动化测试时,偶尔需要用到下载功能,但浏览器的下载可能会弹出下载窗口,或者下载路径不是我们想要保存的位置,所以在通过Selenium启动浏览器时需要做相关的设置,将使这些设置在启动的浏览器中生效果。

下图为Firefox的下载弹窗:

Selenium 设置浏览器下载 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抓包。

Selenium 设置浏览器下载 Firefox 和Chrome

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    设置为文件下载路径