下面列出了怎么用org.openqa.selenium.chrome.ChromeOptions的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public WebDriver getRemoteWebDriver(DesiredCapabilities desiredCapabilities)
{
DesiredCapabilities mergedDesiredCapabilities = getWebDriverCapabilities(false, desiredCapabilities);
WebDriverType webDriverType = WebDriverManager.detectType(mergedDesiredCapabilities);
Capabilities capabilities = mergedDesiredCapabilities;
if (webDriverType != null)
{
webDriverType.prepareCapabilities(mergedDesiredCapabilities);
if (webDriverType == WebDriverType.CHROME)
{
WebDriverConfiguration configuration = getWebDriverConfiguration(webDriverType, false);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(configuration.getCommandLineArguments());
configuration.getExperimentalOptions().forEach(chromeOptions::setExperimentalOption);
capabilities = chromeOptions.merge(mergedDesiredCapabilities);
}
}
return createWebDriver(remoteWebDriverFactory.getRemoteWebDriver(remoteDriverUrl, capabilities));
}
@Test
public void recordingTestThatShouldBeRecordedButNotPersisted() {
try (
// withRecordingFileFactory {
BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
// }
.withCapabilities(new ChromeOptions())
// withRecordingFileFactory {
.withRecordingFileFactory(new CustomRecordingFileFactory())
// }
) {
chrome.start();
doSimpleExplore(chrome);
}
}
private void setChromeDriver() {
ChromeOptions options = new ChromeOptions();
List<String> chromeOptions = new ArrayList<>();
LoggingPreferences logPrefs = new LoggingPreferences();
chromeOptions.add(String.format("--proxy-server=%s", proxies.getCurrentProxyModel().getIp()));
chromeOptions.add(String.format("--user-agent=%s", userAgent.randomUA()));
chromeOptions.add("--mute-audio");
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.addArguments(chromeOptions);
options.setBinary(this.driverLocation);
options.setHeadless(true);
// options.setProxy(this.proxies.getCurrentProxy());
options.setCapability("proxy", this.proxies.getCurrentProxy());
this.webDriver = new ChromeDriver(options);
Log.WINFO(this.workerName, this.workerColor, "Chrome Driver Set.");
}
/**
* Start the Selenium chrome driver instance with lean options
*/
public void startDriver(){
if (serviceManager != null){
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.managed_default_content_settings.images", 2);
options.setExperimentalOption("prefs", prefs);
driver = new RemoteWebDriver(serviceManager.getService().getUrl(), options);
driver.manage().timeouts().implicitlyWait(PAGE_WAIT_TIMEOUT, TimeUnit.SECONDS); // Wait for the page to be completely loaded. Or reasonably loaded.
}
else {
System.err.println("[JS-SRI][-] You must set a driver service manager before you can start a driver.");
}
}
@Test
public void simpleUserInteractionInGoogleChrome(){
String currentDir = System.getProperty("user.dir");
// amend this for your location of chromedriver
String chromeDriverLocation = currentDir + "/../tools/chromedriver/chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromeDriverLocation);
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-plugins");
options.addArguments("disable-extensions");
driver = new ChromeDriver(options);
checkSimpleCtrlBInteractionWorks();
}
public void createDriver(String pkg_name, String sn) {
if(this.driver == null) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("androidPackage", pkg_name);
// chromeOptions.setExperimentalOption("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
// chromeOptions.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
chromeOptions.setExperimentalOption("androidUseRunningApp", true);
chromeOptions.setExperimentalOption("androidDeviceSerial", sn);
// Map<String, Object> chromeOptions = new HashMap<String, Object>();
// chromeOptions.put("androidPackage", "com.eg.android.AlipayGphoneRC");
// chromeOptions.put("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
// capabilities.setCapability(CapabilityType., value);
if(ChromeService.getService() != null)
driver = new RobotRemoteWebDriver(ChromeService.getService().getUrl(), capabilities);
}
}
@BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver",
"./src/test/resources/drivers/chromedriver");
Map<String, Object> deviceMetrics = new HashMap<>();
deviceMetrics.put("width", 411);
deviceMetrics.put("height", 823);
deviceMetrics.put("pixelRatio", 3.0);
Map<String, Object> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 8.0.0;" +
"Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/67.0.3396.99 Mobile Safari/537.36");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
driver = new ChromeDriver(chromeOptions);
driver.get("http://demo-store.seleniumacademy.com/");
}
@Override
protected Capabilities newCaps(Capabilities capsToMerge) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--ignore-certificate-errors");
chromeOptions.addArguments("no-default-browser-check");
// **** 以上capabilities可被传入的caps覆盖 ****
chromeOptions.merge(capsToMerge);
// **** 以下capabilities具有更高优先级,将覆盖传入的caps ****
if (!StringUtils.isEmpty(browser.getPath())) {
chromeOptions.setBinary(browser.getPath());
}
return chromeOptions;
}
public static WebDriver createDriver(String mvnParameter){
if (mvnParameter == null){
System.setProperty(Browsers.CHROME_MAC.getBrowserType(),
OperationSystems.MAC_OS_X.getDriversPath().concat(Browsers.CHROME_MAC.getExecutable()));
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen", "--disable-gpu");
return new ChromeDriver(options);
}
try {
String soName = getSoName();
String browserType = getBrowserTypeFromParameter(mvnParameter);
System.setProperty(browserType, getDriversPath(soName).concat(getFullExecutableNameFromParameter(mvnParameter)));
}catch (Exception e){
System.out.println("ERROR: Please select one of the valid browsers for the test.");
Browsers.showAvaliableBrowsersOptions();
System.exit(1);
}
return Browsers.valueOf(mvnParameter).createDriverInstance();
}
public void setUp() throws MalformedURLException {
String username = System.getenv("SAUCE_USERNAME");
String accessKey = System.getenv("SAUCE_ACCESS_KEY");
ChromeOptions chromeOpts = new ChromeOptions();
chromeOpts.setExperimentalOption("w3c", true);
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("username", username);
sauceOpts.setCapability("accessKey", accessKey);
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(ChromeOptions.CAPABILITY, chromeOpts);
caps.setCapability("sauce:options", sauceOpts);
caps.setCapability("browserName", "googlechrome");
caps.setCapability("browserVersion", "latest");
caps.setCapability("platformName", "windows 10");
String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
URL url = new URL(sauceUrl);
driver = new RemoteWebDriver(url, caps);
}
private ChromeOptions setChromeOptions(ClientProperties properties){
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
// for downloading with Chrome
if(properties.getDownloadFolder() != null) {
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", properties.getDownloadFolder());
}
if(properties.shouldEnableFlash()) {
chromePrefs.put("profile.default_content_setting_values.plugins",1);
chromePrefs.put("profile.content_settings.plugin_whitelist.adobe-flash-player",1);
chromePrefs.put("profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player",1);
}
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", chromePrefs);
return chromeOptions;
}
private static ChromeDriver createChromeDriver() {
ChromeOptions options = new ChromeOptions();
if (BrowserConfig.getChromeBinPath() != null) {
options.setBinary(BrowserConfig.getChromeBinPath().toFile());
}
if (BrowserConfig.getChromeDriverPath() != null) {
System.setProperty(CHROME_DRIVER_PATH_KEY, BrowserConfig.getChromeDriverPath().toString());
}
if (BrowserConfig.isHeadless()) {
options.addArguments("--headless");
options.addArguments("--disable-gpu");
}
if (System.getProperty(CHROME_DRIVER_PATH_KEY) == null) {
setupDriverManagerConfig();
downloadDriverMessage("chrome");
WebDriverManager.chromedriver().setup();
}
return new ChromeDriver(options);
}
public static DesiredCapabilities build(RemoteCapability capability){
DesiredCapabilities desiredCapabilities;
if(RemoteCapability.CHROME.equals(capability)){
ChromeOptions options = new ChromeOptions();
desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
return desiredCapabilities;
} else if (RemoteCapability.FIREFOX.equals(capability)){
FirefoxProfile profile = new FirefoxProfile();
desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, profile);
return desiredCapabilities;
} else if (RemoteCapability.INTERNET_EXPLORER.equals(capability)){
desiredCapabilities = DesiredCapabilities.internetExplorer();
return desiredCapabilities;
} else if (RemoteCapability.PHANTOMJS.equals(capability)){
desiredCapabilities = DesiredCapabilities.phantomjs();
return desiredCapabilities;
}
throw new IllegalArgumentException("No such capability");
}
@Test
public void test() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(NUM_THREADS);
ExecutorService executorService = newFixedThreadPool(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
executorService.submit(() -> {
try {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get(
"https://bonigarcia.github.io/selenium-jupiter/");
String title = driver.getTitle();
System.out.println(title);
driver.quit();
} finally {
latch.countDown();
}
});
}
latch.await();
executorService.shutdown();
}
@Test
public void honorPresetNoProxyEnvironment() {
try (
BrowserWebDriverContainer chromeWithNoProxySet = (BrowserWebDriverContainer) new BrowserWebDriverContainer()
.withCapabilities(new ChromeOptions())
.withEnv(NO_PROXY_KEY, NO_PROXY_VALUE)
) {
chromeWithNoProxySet.start();
Object noProxy = chromeWithNoProxySet.getEnvMap().get(NO_PROXY_KEY);
assertEquals("no_proxy should be preserved by the container rule", NO_PROXY_VALUE, noProxy);
}
}
@Test
public void recordingTestThatShouldBeRecordedAndRetained() {
File target = vncRecordingDirectory.getRoot();
try (
// recordFailing {
// or if you only want videos for test failures:
BrowserWebDriverContainer chrome = new BrowserWebDriverContainer()
.withCapabilities(new ChromeOptions())
.withRecordingMode(RECORD_FAILING, target)
// }
.withRecordingFileFactory(new DefaultRecordingFileFactory())
) {
chrome.start();
doSimpleExplore(chrome);
chrome.afterTest(new TestDescription() {
@Override
public String getTestId() {
return getFilesystemFriendlyName();
}
@Override
public String getFilesystemFriendlyName() {
return "ChromeThatRecordsFailingTests-recordingTestThatShouldBeRecordedAndRetained";
}
}, Optional.of(new RuntimeException("Force writing of video file.")));
String[] files = vncRecordingDirectory.getRoot().list(new PatternFilenameFilter("FAILED-.*\\.flv"));
assertEquals("Recorded file not found", 1, files.length);
}
}
@Test
void testGetRemoteWebDriverIsChromeWithAdditionalOptions() throws Exception
{
String args = "disable-blink-features=BlockCredentialedSubresources";
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(args);
chromeOptions.setExperimentalOption("w3c", Boolean.TRUE);
lenient().doReturn(args).when(propertyParser).getPropertyValue(
String.format(COMMAND_LINE_ARGUMENTS_PROPERTY_FORMAT, WebDriverType.CHROME));
lenient().doReturn("{\"w3c\":true}").when(propertyParser).getPropertyValue(
String.format(EXPERIMENTAL_OPTIONS_PROPERTY_FORMAT, WebDriverType.CHROME));
testGetRemoteWebDriverIsChrome(chromeOptions);
}
private static void testGetChromeWebDriver(WebDriverConfiguration configuration, ChromeOptions chromeOptions)
throws Exception
{
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
ChromeDriver expected = mock(ChromeDriver.class);
whenNew(ChromeDriver.class).withParameterTypes(ChromeOptions.class).withArguments(chromeOptions)
.thenReturn(expected);
WebDriver actual = WebDriverType.CHROME.getWebDriver(desiredCapabilities, configuration);
assertEquals(expected, actual);
}
@Override
public ChromeOptions getCapabilities() {
ChromeOptions chromeOptions = new ChromeOptions();
setChromePrefs(chromeOptions);
setCapabilities(chromeOptions);
setChromeArgs(chromeOptions);
chromeOptions.setPageLoadStrategy(getPageLoadStrategy());
return chromeOptions;
}
private void setChromePrefs(ChromeOptions options){
HashMap<String, Object> chromePrefs = new HashMap<>();
Map<String, Object> configOptions = getBrowserOptions();
configOptions.forEach((key, value) -> {
if (key.equals(getDownloadDirCapabilityKey())) {
chromePrefs.put(key, getDownloadDir());
} else {
chromePrefs.put(key, value);
}
});
options.setExperimentalOption("prefs", chromePrefs);
}
@Override
public ChromeOptions getCapabilities() {
if (!APP_PATH.isSpecified()) {
throw new IllegalStateException(
"App path must be specified when using Electron!");
}
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary(APP_PATH.getValue());
return chromeOptions;
}
@Override
public ChromeOptions getCapabilities() {
ChromeOptions chromeOptions = new ChromeOptions();
// useful defaults
chromeOptions.setCapability(
"chrome.switches",
Collections.singletonList("--no-default-browser-check"));
chromeOptions.setCapability(
"chrome.prefs",
ImmutableMap.of("profile.password_manager_enabled", "false"));
// Workaround Docker/Travis issue
if (Boolean.parseBoolean(System.getenv("CHROME_NO_SANDBOX"))) {
chromeOptions.addArguments("--no-sandbox");
}
// Use Chrome's built in device emulators
if (Property.DEVICE.isSpecified()) {
chromeOptions.setExperimentalOption(
"mobileEmulation",
ImmutableMap.of("deviceName", Property.DEVICE.getValue()));
}
chromeOptions.setHeadless(Property.HEADLESS.getBoolean());
return chromeOptions;
}
private static ChromeOptions generateCustomScreenChromeOptions(String screenToCapture, boolean runningAsRoot,
Path audioFileLocation) {
ChromeOptions options = new ChromeOptions();
// This flag selects the entire screen as video source when screen sharing
options.addArguments("--auto-select-desktop-capture-source=" + screenToCapture);
options.addArguments("--use-fake-device-for-media-stream");
options.addArguments("--use-file-for-fake-audio-capture=" + audioFileLocation.toString());
if (runningAsRoot) {
options.addArguments("--no-sandbox");
}
return options;
}
@BeforeEach
public void createDriver() {
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
WebDriver delegate = new ChromeDriver(options);
Config config = ConfigFactory.load("test.conf");
SelfHealingEngine engine = new SelfHealingEngine(delegate, config);
driver = SelfHealingDriver.create(engine);
}
private static WebDriver setupChromeDriver() throws MalformedURLException {
LOG.i("Setting up Chrome driver...");
System.setProperty("webdriver.chrome.silentOutput", "true");
setupDriver(chromedriver());
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--dns-prefetch-disable");
if (appSetting().isHeadlessMode()) {
chromeOptions.addArguments("--headless");
}
chromeOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
final ChromeDriverService chromeService = ChromeDriverService.createDefaultService();
return new ChromeDriver(chromeService, chromeOptions);
}
@BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver",
"./src/test/resources/drivers/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
driver = new ChromeDriver(chromeOptions);
driver.get("http://demo-store.seleniumacademy.com/");
}
@Before
public void setupTest() {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
driver = new ChromeDriver(chromeOptions);
wait = new WebDriverWait(driver, Duration.ofSeconds(5));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private Capabilities createCapabilities() {
String property = System.getProperty("selenium.browser", "ff");
Browser browser = Browser.detect();
switch (browser) {
case CHROME:
return new ChromeOptions();
case EDGE:
return new EdgeHtmlOptions();
case CHROMIUMEDGE:
return new EdgeOptions();
case IE:
return new InternetExplorerOptions();
case FIREFOX:
case MARIONETTE:
return new FirefoxOptions();
case OPERA:
case OPERABLINK:
return new OperaOptions();
case SAFARI:
return new SafariOptions();
default:
fail("Attempt to use an unsupported browser: " + property);
// we never get here, but keep null checks happy anyway
return new DesiredCapabilities();
}
}
@Before
public void setupTest() {
ChromeOptions options = new ChromeOptions();
// This flag avoids to grant the user media
options.addArguments("--use-fake-ui-for-media-stream");
// This flag fakes user media with synthetic video (green with spinner
// and timer)
options.addArguments("--use-fake-device-for-media-stream");
driver = new ChromeDriver(options);
}
@Before
public void beforeTest() {
logger.info("Test setup...");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
// driver = new ChromeDriver(chromeOptions);
if (logger.isDebugEnabled()) {
logger.debug("Initialising ChromeDriver...");
}
driver = new RemoteWebDriver(CucumberFeatureTest.getService().getUrl(), chromeOptions);
_jsExecutor = (JavascriptExecutor) driver;
logger.info("Test setup complete.");
}