如果您对org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75感兴趣
如果您对org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75的详细内容,并且为您提供关于java – Selenium 3.0 Firefx驱动程序失败与org.openqa.selenium.SessionNotCreatedException无法创建新的远程会话、org.openqa.selenium.chrome.ChromeDriverService的实例源码、org.openqa.selenium.chrome.ChromeDriver的实例源码、org.openqa.selenium.SessionNotCreatedException的实例源码的有价值信息。
本文目录一览:- org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75
- java – Selenium 3.0 Firefx驱动程序失败与org.openqa.selenium.SessionNotCreatedException无法创建新的远程会话
- org.openqa.selenium.chrome.ChromeDriverService的实例源码
- org.openqa.selenium.chrome.ChromeDriver的实例源码
- org.openqa.selenium.SessionNotCreatedException的实例源码
org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75
我想打开显示错误的Chrome浏览器。
import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;public class Homepage { public static void main(String[] args) { // TODO Auto-generated method stub //Create Driver object System.setProperty("webdriver.chrome.driver", "C:\\Workdirectory\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); }}
在这里,我期待的是我的Chrome浏览器,但会引发类似
Starting ChromeDriver 75.0.3770.8 (681f24ea911fe754973dda2fdc6d2a2e159dd300-refs/branch-heads/3770@{#40}) on port 21714Only local connections are allowed.Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75Build info: version: ''3.141.59'', revision: ''e82be7d358'', time: ''2018-11-14T08:25:48''System info: host: ''DESKTOP-3JIP3OF'', ip: ''192.168.1.73'', os.name: ''Windows 10'', os.arch: ''amd64'', os.version: ''10.0'', java.version: ''1.8.0_101''Driver info: driver.version: ChromeDriver
答案1
小编典典此错误消息…
org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75
…暗示 ChromeDriver v75 仅支持 Chrome浏览器v75 ,而该功能在您的系统中不可用。
您的主要问题是所使用的二进制版本之间的 不兼容性 ,如下所示:
- 您正在使用 chromedriver = 75.0.3770.8
- chromedriver = 75.0.3770.8的 发行说明中明确提到以下内容:
支持 Chrome版本75
- 您当前正在使用的最新发布的 Chrome 版本是 chrome = 74.0 。
因此, ChromeDriver v75.0 和 Chrome浏览器v74.0 之间存在明显的不匹配 __
解
- 降级 ChromeDriver 到 ChromeDriver v74.0水平。
- 将 Chrome 版本保持在 Chrome v74.0 级别。(根据ChromeDriver v74.0发行说明)
- 执行您的
@Test
。
java – Selenium 3.0 Firefx驱动程序失败与org.openqa.selenium.SessionNotCreatedException无法创建新的远程会话
System.setProperty("webdriver.gecko.driver","..<Path>../geckodriver.exe"); capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("marionette",true); driver = new FirefoxDriver(capabilities); Caused by: org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true,firefoxOptions=org.openqa.selenium.firefox.FirefoxOptions@23aa363a,browserName=firefox,moz:firefoxOptions=org.openqa.selenium.firefox.FirefoxOptions@23aa363a,version=,platform=ANY}],required capabilities = Capabilities [{}] Build info: version: '3.0.0',revision: '350cf60',time: '2016-10-13 10:48:57 -0700' System info: host: 'D202540',ip: '10.22.19.193',os.name: 'Windows 7',os.arch: 'amd64',os.version: '6.1',java.version: '1.8.0_45' Driver info: driver.version: FirefoxDriver at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:91) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:241) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:128) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:259) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:247) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:242) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:135)
解决方法
System.setProperty("webdriver.gecko.driver","path\\to\\geckodriver.exe")
检查这个link.
org.openqa.selenium.chrome.ChromeDriverService的实例源码
@Override public WebDriver createDriver() throws Exception { final ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--no-sandBox"); if (headless) { chromeOptions.setHeadless(true); } final Map<String,String> environmentvariables = new HashMap<>(); if (!headless && xvfbPort != null) { environmentvariables.put("disPLAY",":" + String.valueOf(xvfbPort)); } final ChromeDriverService service = new ChromeDriverService.Builder() .usingAnyFreePort() .withEnvironment(environmentvariables) .build(); final WebDriver driver = new ChromeDriver(service,chromeOptions); manage(driver); return driver; }
private static void initializeSeleniumDriver() throws IOException { if (DRIVERSERVICE == null) { String theChromeDriverBinary = System.getenv("CHROMEDRIVER_BINARY"); if (theChromeDriverBinary == null || theChromeDriverBinary.isEmpty()) { throw new RuntimeException("No chromedriver binary found! Please set CHROMEDRIVER_BINARY environment variable!"); } ChromeDriverService.Builder theDriverService = new ChromeDriverService.Builder(); theDriverService = theDriverService.withVerbose(false); theDriverService = theDriverService.usingDriverExecutable(new File(theChromeDriverBinary)); DRIVERSERVICE = theDriverService.build(); DRIVERSERVICE.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> DRIVERSERVICE.stop())); } }
/** * Creates an wrapper of the given real {@link IDevice device}. * * @param devicetoWrap * - device to be wrapped * @param executor * - an {@link ExecutorService} used for async tasks * @param shellCommandExecutor * - an executor of shell commands for the wrapped device * @param serviceCommunicator * - a communicator to the service component on the device * @param automatorCommunicator * - a communicator to the UI automator component on the device * @param chromeDriverService * - the service component of the ChromeDriver * @param fileRecycler * - responsible for removing obsolete files * @param ftpFileTransferService * - responsible for file transfers to the FTP server * @throws NotPossibleForDeviceException * - thrown when Cannot create real wrap device for an emulator. */ public RealWrapDevice(IDevice devicetoWrap,ExecutorService executor,BackgroundShellCommandExecutor shellCommandExecutor,ServiceCommunicator serviceCommunicator,UIAutomatorCommunicator automatorCommunicator,ChromeDriverService chromeDriverService,FileRecycler fileRecycler,FtpFileTransferService ftpFileTransferService) throws NotPossibleForDeviceException { super(devicetoWrap,executor,shellCommandExecutor,serviceCommunicator,automatorCommunicator,chromeDriverService,fileRecycler,ftpFileTransferService); if (devicetoWrap.isEmulator()) { throw new NotPossibleForDeviceException("Cannot create real wrap device for an emulator."); } }
public FakeWrapDevice(IDevice devicetoWrap,FtpFileTransferService ftpFileTransferService) { super(devicetoWrap,null); }
private synchronized void createAndStartService() { if ((service != null) && service.isRunning()) { return; } File driverFile = new File(ApplicationProperties.CHROME_DRIVER_PATH.getStringVal("./chromedriver.exe")); if (!driverFile.exists()) { logger.error("Please set webdriver.chrome.driver property properly."); throw new AutomationError("Driver file not exist."); } try { System.setProperty("webdriver.chrome.driver",driverFile.getCanonicalPath()); service = ChromeDriverService.createDefaultService(); service.start(); } catch (IOException e) { logger.error("Unable to start Chrome driver",e); throw new AutomationError("Unable to start Chrome Driver Service ",e); } }
/** * <p> * <a href="http://code.google.com/p/chromedriver/downloads/list">ChromeDriver downloads</a>,{@see #REMOTE_PUBLIC_CHROME},* {@see #WEBDRIVER_CHROME_DRIVER},and {@see #HUB_DRIVER_PROPERTY} * </p> * * @return chromeDriverService */ public static ChromeDriverService chromeDriverCreateCheck() { String driverParam = System.getProperty(HUB_DRIVER_PROPERTY); // Todo can the saucelabs driver stuff be Leveraged here? if (driverParam != null && "chrome".equals(driverParam.toLowerCase())) { if (System.getProperty(WEBDRIVER_CHROME_DRIVER) == null) { if (System.getProperty(REMOTE_PUBLIC_CHROME) != null) { System.setProperty(WEBDRIVER_CHROME_DRIVER,System.getProperty(REMOTE_PUBLIC_CHROME)); } } try { ChromeDriverService chromeDriverService = new ChromeDriverService.Builder() .usingDriverExecutable(new File(System.getProperty(WEBDRIVER_CHROME_DRIVER))) .usingAnyFreePort() .build(); return chromeDriverService; } catch (Throwable t) { throw new RuntimeException("Exception starting chrome driver service,is chromedriver ( http://code.google.com/p/chromedriver/downloads/list ) installed? You can include the path to it using -Dremote.public.chrome",t) ; } } return null; }
public ChromeDriverService createService(String... args) { Preconditions.checkArgument(args.length % 2 == 0,"arguments should be pairs"); Map<String,String> environment = new HashMap<>(); for (int i = 1; i < args.length; i += 2) { environment.put(args[i - 1],args[i]); } handledisPLAYonLinux(environment); ChromeDriverService service = new Builder() .usingDriverExecutable(locationStrategy.findExecutable()) .withVerbose(log.isDebugEnabled()) .withEnvironment(environment) .usingAnyFreePort() .build(); LoggingOutputStream loggingOutputStream = new LoggingOutputStream(log,LogLevel.INFO); service.sendOutputTo(loggingOutputStream); return service; }
@Test public void startAndStop() throws IOException { ChromeDriverService driverService = factory.createService(); try { driverService.start(); WebDriver webDriver = factory.createWebDriver(driverService); String url = "http://localhost:" + httpServer.getAddress() .getPort() + "/webdriverTest"; webDriver.get(url); assertthat(webDriver.getcurrenturl()).isEqualTo(url); } finally { driverService.stop(); } }
/** * <p> * <a href="http://code.google.com/p/chromedriver/downloads/list">ChromeDriver downloads</a>,t) ; } } return null; }
@Subscribe public void configurebrowser(final BeforeWebDriverCreationEvent event) { switch (browser) { case "firefox": { // configure Firefox } case "chrome": { setPathToDriverIfExistsAndisExecutable(relativePathtochromeDriver,ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY); // configure Chrome break; } case "ie": { setPathToDriverIfExistsAndisExecutable(relativePathToIeDriver,InternetExplorerDriverService.IE_DRIVER_EXE_PROPERTY); // configure InternetExplorer break; } default: { throw new RuntimeException(String.format("Please configure one of the supported browsers in %s",JFunkConstants.SCRIPT_PROPERTIES)); } } }
/** * @link http://code.google.com/p/chromedriver/downloads/list * @link #REMOTE_PUBLIC_CHROME * @link #WEBDRIVER_CHROME_DRIVER * @link ITUtil#HUB_DRIVER_PROPERTY * @return chromeDriverService */ public static ChromeDriverService chromeDriverCreateCheck() { String driverParam = System.getProperty(ITUtil.HUB_DRIVER_PROPERTY); // Todo can the saucelabs driver stuff be Leveraged here? if (driverParam != null && "chrome".equals(driverParam.toLowerCase())) { if (System.getProperty(WEBDRIVER_CHROME_DRIVER) == null) { if (System.getProperty(REMOTE_PUBLIC_CHROME) != null) { System.setProperty(WEBDRIVER_CHROME_DRIVER,t) ; } } return null; }
@BeforeClass public static void createDriver() { String chromeDriverExecutable = "chromedriver"; if (System.getProperty( "os.name" ).toLowerCase(Locale.US).indexOf("windows") > -1) { chromeDriverExecutable += ".exe"; } File chromeDriver = new File("target/chromedriver/" + chromeDriverExecutable); if (!chromeDriver.exists()) { throw new RuntimeException("chromedriver Could not be located!"); } ChromeDriverService chromeDriverService = new ChromeDriverService.Builder() .withVerbose(true) .usingAnyFreePort() .usingDriverExecutable(chromeDriver) .build(); driver = new ChromeDriver(chromeDriverService); }
public ChromeDriverService.Builder createChromeDriverServiceBuilder(SiteConfig siteConfig,DriverConfig driverConfig,File driverFile) { ChromeDriverService.Builder serviceBuilder = new ChromeDriverService.Builder(); serviceBuilder.usingDriverExecutable(driverFile); serviceBuilder.usingAnyFreePort(); // serviceBuilder.usingPort(int) // serviceBuilder.withVerbose(boolean); // serviceBuilder.withLogFile(File) // serviceBuilder.withEnvironment(Map<String,String>) // serviceBuilder.withSilent(boolean) // serviceBuilder.withWhitelistedIps(String) return serviceBuilder; }
public static void main(String[] args) { //设置相应的驱动程序的位置 System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,"F:\\selenium\\chromedriver.exe"); System.setProperty(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"F:\\selenium\\phantomjs.exe"); //任务执行线程池大小 int threadCount = 5; SpiderConfig spiderConfig = SpiderConfig.create("baidu",threadCount) .setEmptySleepMillis(1000) .setExitWhenComplete(true); SiteConfig siteConfig = SiteConfig.create() .setMaxConnTotal(200) .setMaxConnPerRoute(100); //定义WebDriver池 WebDriverPool webDriverPool = new WebDriverPool( new WebDriverFactory(),new DefaultWebDriverChooser(DriverType.CHROME),threadCount); //使用WebDriverDownloader请求任务下载器 Downloader downloader = new WebDriverDownloader(webDriverPool); Spider spider = Spider.create(spiderConfig,siteConfig,new BaiduPageProcessor()) .setDownloader(downloader) //设置请求任务下载器 .setPipeline(new BaiduPipeline()) .addStartRequests("https://www.baidu.com/s?wd=https"); //监控 SpiderMonitor.register(spider); //启动 spider.start(); }
@Bean(destroyMethod = "stop") @Lazy public ChromeDriverService chromeDriverService() { System.setProperty("webdriver.chrome.driver","ext/chromedriver"); return createDefaultService(); }
/** * Generates a chrome webdriver. * * @param headlessMode * Enable headless mode ? * @return * A chrome webdriver * @throws TechnicalException * if an error occured when Webdriver setExecutable to true. */ private WebDriver generateGoogleChromeDriver(boolean headlessMode) throws TechnicalException { final String pathWebdriver = DriverFactory.getPath(Driver.CHROME); if (!new File(pathWebdriver).setExecutable(true)) { throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE)); } logger.info("Generating Chrome driver ({}) ...",pathWebdriver); System.setProperty(Driver.CHROME.getDriverName(),pathWebdriver); final ChromeOptions chromeOptions = new ChromeOptions(); final DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION,true); capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIoUR,UnexpecteDalertBehavIoUr.ACCEPT); setLoggingLevel(capabilities); if (Context.isHeadless()) { chromeOptions.addArguments("--headless"); } // Proxy configuration if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) { capabilities.setCapability(CapabilityType.PROXY,Context.getProxy()); } setChromeOptions(capabilities,chromeOptions); String withWhitelistedIps = Context.getWebdriversProperties("withWhitelistedIps"); if (withWhitelistedIps != null && !"".equals(withWhitelistedIps)) { ChromeDriverService service = new ChromeDriverService.Builder().withWhitelistedIps(withWhitelistedIps).withVerbose(false).build(); return new ChromeDriver(service,capabilities); } else { return new ChromeDriver(capabilities); } }
public static ChromeDriverService createDriverService() throws IOException { ChromeDriverService service = new ChromeDriverService.Builder() .usingDriverExecutable(new File(System.getProperty("user.dir") + separator + "misc" + separator + "chromedriver.exe")) .usingAnyFreePort() .build(); service.start(); return service; }
public void launchChromeDriver() { System.setProperty("webdriver.chrome.driver",this.config.getString("driver")); ChromeOptions chromeParams = new ChromeOptions(); JSONArray options = this.config.getJSONArray("chromeParams"); if(options != null) { for(int i = 0; i < options.length(); i++) { chromeParams.addArguments(options.getString(i)); } } if(this.config.optString("chrome",null) != null) { chromeParams.setBinary(this.config.getString("chrome")); } try { if(! Util.isUnix()) { this.chromeDriver = new ChromeDriver(chromeParams); } else { this.chromeDriver = new ChromeDriver(new ChromeDriverService.Builder().withEnvironment(ImmutableMap.of("disPLAY",":0.0")).build(),chromeParams); } } catch(Exception e) { System.out.println("Error loading chromedriver. Are you sure the correct path is set in config.json?"); e.printstacktrace(); System.exit(0); } }
@Test public void canStartDriverService() throws Exception { String pathToDriver = "chromedriver"; String screenToUse = ":1"; ChromeDriverService.Builder builder = mock(ChromeDriverService.Builder.class,RETURNS_MOCKS); ChromeDriverServicesupplier chromeDriverServicesupplier = new ChromeDriverServicesupplier(); whenNew(ChromeDriverService.Builder.class).withNoArguments().thenReturn(builder); chromeDriverServicesupplier.getDriverService(pathToDriver,screenToUse); verify(builder).usingDriverExecutable(eq(new File(pathToDriver))); }
@Test public void callsTheCorrectConstructor() throws Exception { ChromeDriverService chromeDriverService = mock(ChromeDriverService.class); DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class); ChromeDriver expected = mock(ChromeDriver.class); whenNew(ChromeDriver.class).withArguments(chromeDriverService,desiredCapabilities).thenReturn(expected); ChromeDriversupplier chromeDriversupplier = new ChromeDriversupplier(); WebDriver actual = chromeDriversupplier.get(chromeDriverService,desiredCapabilities); assertEquals(expected,actual); }
/** * Starts WebDriver service. * * For perfomance reasons,this method should be called once before the entire testing session rather than * before each test. */ public void initialise() { chromeDriverService = new ChromeDriverService.Builder() .usingAnyFreePort() .usingDriverExecutable(getChromedriverFileLocation()) .build(); try { chromeDriverService.start(); } catch (final IOException e) { throw new UncheckedioException(e); } }
private ChromeDriverService getChromeDriverService() { if (chromeDriverService == null) { throw new IllegalStateException( "WebDriverService hasn't been initialised,yet. Have you forgotten to call 'initialise()' first?"); } return chromeDriverService; }
public DebateFetcher(String chromeDriverFile) throws IOException { service = new ChromeDriverService.Builder() .usingDriverExecutable( new File(chromeDriverFile)) .usingAnyFreePort() .withEnvironment(ImmutableMap.of("disPLAY",":20")).build(); service.start(); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); driver = new RemoteWebDriver(service.getUrl(),capabilities); }
public static DesiredCapabilities getChromeCapabilities() { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setJavascriptEnabled(true); capabilities.setCapability("acceptSslCerts",true); capabilities.setCapability("takesScreenshot",true); capabilities.setCapability(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,asList("--ignore-ssl-errors=true")); LoggingPreferences loggingPreferences = new LoggingPreferences(); loggingPreferences.enable(LogType.broWSER,Level.ALL); capabilities.setCapability(CapabilityType.LOGGING_PREFS,loggingPreferences); return capabilities; }
/** * Creates an abstract wrapper of the given {@link IDevice device}. * * @param devicetoWrap * - device to be wrapped * @param executor * - an {@link ExecutorService} used for async tasks * @param shellCommandExecutor * - an executor of shell commands for the wrapped device * @param serviceCommunicator * - a communicator to the service component on the device * @param automatorCommunicator * - a communicator to the UI automator component on the device * @param chromeDriverService * - the service component of the ChromeDriver * @param fileRecycler * - responsible for removing obsolete files * @param ftpFileTransferService * - responsible for file transfers to the FTP server */ public AbstractWrapDevice(IDevice devicetoWrap,FtpFileTransferService ftpFileTransferService) { // Todo: Use a dependency injection mechanism here. this.wrappedDevice = devicetoWrap; this.executor = executor; this.shellCommandExecutor = shellCommandExecutor; this.serviceCommunicator = serviceCommunicator; this.automatorCommunicator = automatorCommunicator; this.fileRecycler = fileRecycler; this.logcatBuffer = new Buffer<String,Pair<Integer,String>>(); this.ftpFileTransferService = ftpFileTransferService; transferService = new FileTransferService(wrappedDevice); apkInstaller = new ApkInstaller(wrappedDevice); imeManager = new ImeManager(shellCommandExecutor); pullFileCompletionService = new ExecutorCompletionService<>(executor); webElementManager = new WebElementManager(chromeDriverService,devicetoWrap.getSerialNumber()); deviceinformation = getDeviceinformation(); try { setupDeviceEntities(deviceinformation); } catch (UnresolvedEntityTypeException e) { LOGGER.warn(e.getMessage()); } }
private static void initializeChromeVariables() { final URL resource = DriverFactory.class.getClassLoader().getResource("drivers"); final String chromeExecutableFolder = resource.getPath() + File.separator + environment(); if (environment().equals("windows")) { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,chromeExecutableFolder + File.separator + "chromedriver.exe"); } else { final File chromeExecutable = new File(chromeExecutableFolder,"chromedriver"); chromeExecutable.setExecutable(true); System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,chromeExecutable.getAbsolutePath()); } }
private static WebDriver allocateChromeInstance(browserModel model,Locale lang) throws IOException { DesiredCapabilities dc; switch(model) { default: throw new IllegalStateException("Unsupported browser type " + model.getCode() + " for local execution"); case CHROME: dc = getChromeCapabilities(lang); break; case CHROME_HEADLESS: dc = getChromeHeadlessCapabilities(lang); break; } TestProperties tp = TUtilTestProperties.getTestProperties(); String chromeBinariesLocation = tp.getProperty("webdriver.chrome.driver","/usr/bin/google-chrome"); System.setProperty("webdriver.chromedriver",chromeBinariesLocation); dc.setCapability("chrome.binary",chromeBinariesLocation); //-- Set the XDG_CONfig_HOME envvar; this is used by fontconfig as one of its locations File dir = createFontConfigFile(); Map<String,String> env = new HashMap<>(); env.put("XDG_CONfig_HOME",dir.getParentFile().getAbsolutePath()); Builder builder = new Builder(); builder.usingAnyFreePort(); builder.withEnvironment(env); ChromeDriverService service = builder.build(); MyChromeDriver chromeDriver = new MyChromeDriver(service,dc); chromeDriver.manage().window().setSize(new Dimension(1280,1024)); String browserName = chromeDriver.getCapabilities().getbrowserName(); String version = chromeDriver.getCapabilities().getVersion(); System.out.println("wd: allocated " + browserName + " " + version); return chromeDriver; }
public MyChromeDriver(ChromeDriverService service,Capabilities capabilities) { super(new MyChromeDriverCommandExecutor(service),capabilities); this.locationContext = new RemoteLocationContext(this.getExecuteMethod()); this.webStorage = new RemoteWebStorage(this.getExecuteMethod()); this.touchScreen = new RemotetouchScreen(this.getExecuteMethod()); this.networkConnection = new RemoteNetworkConnection(this.getExecuteMethod()); }
@Test public void environmentvariableShouldBePropagated() throws NoSuchFieldException,illegalaccessexception { ChromeDriverService service = serviceFactory.createService("disPLAY","X"); Map<String,String> env = getEnvFromDriverService(service); assertthat(env).containsEntry("disPLAY","X"); }
@Test public void onLinux_shouldSetdisplayToZEROIfUnset() throws NoSuchFieldException,illegalaccessexception { environmentvariables.set("disPLAY",null); environmentvariables.set("os.name","Linux"); ChromeDriverService service = serviceFactory.createService(); Map<String,":0"); }
@Test public void onLinux_shouldUsedisplayFromEnvironment() throws NoSuchFieldException,"Y"); environmentvariables.set("os.name","Y"); }
/** * Starts a selenium service for a given browser * @param browser The browser to start the service for * @return * @throws IOException */ public static DriverService start(browser browser) throws IOException { browserDriverProvider provider = getProvider(browser); DriverService service = new ChromeDriverService.Builder().usingDriverExecutable(provider.getDriverFile()).usingAnyFreePort().build(); service.start(); return service; }
private WebDriver getChromeConfigurado(String proxy) { DesiredCapabilities capabilities = new DesiredCapabilities(); ArrayList<String> switches = new ArrayList<String>(); //Habilitar todas as extens�es,mas o problema que n�o carrega o proxy correto //switches.add("--user-data-dir="+System.getProperty("user.home")+"\\AppData\\Local\\Google\\Chrome\\User Data"); //switches.add("--load-extension="+System.getProperty("user.home")+"\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\chklaanhfefbnpoihckbnefhakgolnmc\\0.0.32_0"); if (!(proxy.equals(""))) { System.out.println("Passou aqui"); switches.add("--proxy-server=" + "http://" + proxy); } else { System.out.println("Voc� n�o est� usando proxy!"); } switches.add("--ignore-certificate-errors"); switches.add("--start-maximized"); //switches.add("--disable-extensions"); Desabilitar todas as extens�es. capabilities.setbrowserName("chrome"); capabilities.setJavascriptEnabled(true); capabilities.setCapability("chrome.switches",switches); chromeService = new ChromeDriverService.Builder() .usingDriverExecutable(new File(InterNavegador.PATH_CHROME)) .usingAnyFreePort().build(); try { chromeService.start(); } catch (IOException e) { System.out.println(e); } return new RemoteWebDriver(chromeService.getUrl(),capabilities); }
protected WebDriver getChromeWebDriver() { String pathToDriverBin = getosspecificBinaryPathFromProp(CHROME_DRIVER_BIN_PROP,"chromedriver"); System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY,pathToDriverBin); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); return new ChromeDriver(capabilities); }
@Override protected DriverService createDriverService() { Builder builder = new ChromeDriverService.Builder(); if (port != null) builder.usingPort(port); if (driverExecutable != null) builder.usingDriverExecutable(driverExecutable); if (environment != null) builder.withEnvironment(environment); if (logFile != null) builder.withLogFile(logFile); if (verbose != null) builder.withVerbose(verbose); if (silent != null) builder.withSilent(silent); return builder.build(); }
protected ChromeDriverService start() throws IOException { if (service != null) throw new IllegalStateException(); ChromeDriverService newService = ChromeDriverService.createDefaultService(); newService.start(); Runtime.getRuntime().addShutdownHook(getNewShutdownHookThread()); return newService; }
public WebDriverEx createChromeWebDriver(SiteConfig siteConfig,DriverConfig driverConfig) throws IOException { File driverFile = createDriverFile(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY); DesiredCapabilities desiredCapabilities = createChromeDesiredCapabilities(siteConfig,driverConfig); ChromeDriverService driverService = createChromeDriverService(siteConfig,driverConfig,driverFile); return createWebDriver(driverService,desiredCapabilities,driverConfig); }
public ChromeDriverService createChromeDriverService(SiteConfig siteConfig,File driverFile) { return createChromeDriverServiceBuilder(siteConfig,driverFile).build(); }
public ChromeDriverFactory(ChromeDriverService chromeDriverService,WebDriverConfigurationProperties properties) { this.chromeDriverService = chromeDriverService; this.properties = properties; }
@Override protected DriverService.Builder getBuilder() { return new ChromeDriverService.Builder(); }
org.openqa.selenium.chrome.ChromeDriver的实例源码
public static WebDriver getDriver() { String browser = System.getenv("broWSER"); if (browser == null) { ChromeDriverManager.getInstance().setup(); return new ChromeDriver(); } switch (browser) { case "IE": InternetExplorerDriverManager.getInstance().setup(); return new InternetExplorerDriver(); case "FIREFOX": FirefoxDriverManager.getInstance().setup(); return new FirefoxDriver(); default: ChromeDriverManager.getInstance().setup(); return new ChromeDriver(); } }
public static WebDriver getDriverUsingIf(DesiredCapabilities desiredCapabilities) { if (desiredCapabilities == null) { throw new IllegalStateException("DesiredCapabilities are missing!"); } final String browser = desiredCapabilities.getbrowserName(); if (CHROME.equalsIgnoreCase(browser)) { return new ChromeDriver(desiredCapabilities); } else if (FIREFOX.equalsIgnoreCase(browser)) { return new FirefoxDriver(desiredCapabilities); } else if (browser.isEmpty()) { throw new IllegalStateException("'browser' capability is missing!"); } throw new IllegalArgumentException(desiredCapabilities.getbrowserName() + " browser is not supported!"); }
@BeforeMethod public void siteUp () { final String exe = "chromedriver.exe"; final String path = getClass ().getClassLoader () .getResource (exe) .getPath (); final String webSite = "http://www.naukri.com"; final String binaryPath = "C:\\Users\\DELL\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"; System.setProperty("webdriver.chrome.driver",path); ChromeOptions chromeOpt= new ChromeOptions(); chromeOpt.setBinary(binaryPath); driver = new ChromeDriver (chromeOpt); driver.get(webSite); driver.manage ().timeouts ().implicitlyWait (10,TimeUnit.SECONDS); driver.manage().window().maximize(); windowHandling (); }
@Override public WebDriver createDriver(DesiredCapabilities capabilities) { Map<String,Object> preferences = new Hashtable<>(); preferences.put("profile.default_content_settings.popups",0); preferences.put("download.prompt_for_download","false"); String downloadsPath = System.getProperty("user.home") + "/Downloads"; preferences.put("download.default_directory",loadSystemPropertyOrDefault("fileDownloadpath",downloadsPath)); preferences.put("plugins.plugins_disabled",new String[]{ "Adobe Flash Player","Chrome PDF Viewer"}); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs",preferences); capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true); capabilities.setCapability(ChromeOptions.CAPABILITY,options); return new ChromeDriver(capabilities); }
private ChromeDriver setUp(Properties properties) { System.setProperty("webdriver.chrome.driver",properties.getProperty("webdriver.chrome.driver")); String binaryPath = properties.getProperty(CHROME_DRIVER_BINARY_PATH); if (binaryPath == null) { throw new RuntimeException("Missing property : " + CHROME_DRIVER_BINARY_PATH); } Map<String,Object> prefs = new HashMap<>(); prefs.put("profile.default_content_setting_values.notifications",2); ChromeOptions options = new ChromeOptions(); options.setExperimentalOption("prefs",prefs); options.setBinary(binaryPath); options.addArguments("--headless"); options.addArguments("--user-agent=" + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/60.0.3112.113 Safari/537.36"); return new ChromeDriver(options); }
/** * 对当前对url进行截屏,一方面可以做调试使用看能否进入到该页面,另一方面截屏的图片未来可以做ocr使用 * @param url */ public static void getScreenshot(String url) { //启动chrome实例 WebDriver driver = new ChromeDriver(); driver.get(url); //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。 File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //利用IoUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。 try { IoUtils.copyFile(srcFile,new File("screenshot.png")); } catch (IOException e) { e.printstacktrace(); } //关闭浏览器 driver.quit(); }
public static WebDriver getDriverUsingSwitch() { final String browser = System.getProperty("browser"); if (browser == null || browser.isEmpty()) { throw new IllegalStateException("'browser' property is missing!"); } switch (browser) { case CHROME: return new ChromeDriver(); case FIREFOX: return new FirefoxDriver(); default: throw new IllegalArgumentException(browser + " browser is not supported!"); } }
/** * Создание instance google chrome эмулирующего работу на мобильном устройстве (по умолчанию nexus 5) * Мобильное устройство может быть задано через системные переменные * * @param capabilities настройки Chrome браузера * @return возвращает новый instance Chrome драйера */ @Override public WebDriver createDriver(DesiredCapabilities capabilities) { log.info("---------------run CustomMobileDriver---------------------"); String mobileDeviceName = loadSystemPropertyOrDefault("device","Nexus 5"); Map<String,String> mobileEmulation = new HashMap<>(); mobileEmulation.put("deviceName",mobileDeviceName); Map<String,Object> chromeOptions = new HashMap<>(); chromeOptions.put("mobileEmulation",mobileEmulation); DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome(); desiredCapabilities.setCapability(ChromeOptions.CAPABILITY,chromeOptions); desiredCapabilities.setbrowserName(desiredCapabilities.chrome().getbrowserName()); return new ChromeDriver(desiredCapabilities); }
private WebDriver chrome(Settings settings,DesiredCapabilities customDesiredCapabilities) { ChromeDriverManager.getInstance().setup(); DesiredCapabilities desiredCapabilities = getChromeDesiredCapabilities(settings); if (!customDesiredCapabilities.asMap().isEmpty()) { desiredCapabilities.merge(customDesiredCapabilities); } return new ChromeDriver(desiredCapabilities); }
@Test @NeedRestartDriver public void chrome_config_test() { openPage("main.html",BasePage.class); WebDriver webDriver = ((FramesTransparentWebDriver) SeleniumHolder.getWebDriver()).getWrappedDriver(); Assert.assertTrue(webDriver instanceof ChromeDriver); Assert.assertEquals(((RemoteWebDriver) webDriver).getCapabilities().getCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIoUR),UnexpecteDalertBehavIoUr.IGnorE.toString()); }
@Override public ChromeDriver getobject() throws BeansException { if (properties.getChrome().isEnabled()) { try { return new ChromeDriver(chromeDriverService); } catch (IllegalStateException e) { e.printstacktrace(); // swallow the exception } } return null; }
@Test public void testWithMockedChrome() { load(new Class[]{},"com.greglturnquist.webdriver.firefox.enabled:false","com.greglturnquist.webdriver.safari.enabled:false"); WebDriver driver = context.getBean(WebDriver.class); assertthat(ClassUtils.isAssignable(TakesScreenshot.class,driver.getClass())).isTrue(); assertthat(ClassUtils.isAssignable(ChromeDriver.class,driver.getClass())).isTrue(); }
@BeforeClass public static void setUp() throws IOException { System.setProperty("webdriver.chrome.driver","ext/chromedriver"); service = createDefaultService(); driver = new ChromeDriver(service); Path testResults = Paths.get("build","test-results"); if (!Files.exists(testResults)) { Files.createDirectory(testResults); } }
public static void main(String[] args) throws Exception{ //配置Chromediver System.getProperties().setProperty("webdriver.chrome.driver","chromedriver.exe"); //开启新WebDriver进程 WebDriver webDriver = new ChromeDriver(); //全局隐式等待 webDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); //设定网址 webDriver.get("https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"); //显示等待控制对象 webdriverwait webdriverwait=new webdriverwait(webDriver,10); //等待输入框可用后输入账号密码 webdriverwait.until(ExpectedConditions.elementToBeClickable(By.id("loginName"))).sendKeys(args[0]); webdriverwait.until(ExpectedConditions.elementToBeClickable(By.id("loginPassword"))).sendKeys(args[1]); //点击登录 webDriver.findElement(By.id("loginAction")).click(); //等待2秒用于页面加载,保证Cookie响应全部获取。 sleep(2000); //获取Cookie并打印 Set<Cookie> cookies=webDriver.manage().getCookies(); Iterator iterator=cookies.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next().toString()); } //关闭WebDriver,否则并不自动关闭 webDriver.close(); }
public static void testSelenium() throws Exception { System.getProperties().setProperty("webdriver.chrome.driver","chromedriver.exe"); WebDriver webDriver = new ChromeDriver(); webDriver.get("http://huaban.com/"); Thread.sleep(5000); WebElement webElement = webDriver.findElement(By.xpath("/html")); System.out.println(webElement.getAttribute("outerHTML")); webDriver.close(); }
private void mockProvider(final WebDriverProvider provider,final int duplicatesAmount,final BeforeMethodListener listener) { final WebDriverProvider spyProvider = spy(provider); final WebDriver mockDriver = mock(ChromeDriver.class); doReturn(mockDriver).when(spyProvider).createDriver(any(),any()); final List<WebDriverProvider> providers = duplicatesAmount > 1 ? IntStreamEx.range(0,duplicatesAmount).mapToObj(i -> provider).toList() : singletonList(spyProvider); doReturn(providers).when(listener).getWebDriverProviders(); }
@BeforeEach void init() { //打开chrome浏览器 System.setProperty("webdriver.chrome.driver",Thread.currentThread().getContextClassLoader() .getResource("autotest/" + "chromedriver.exe").getPath()); ChromeOptions options = new ChromeOptions(); options.addArguments("disable-infobars"); d = new ChromeDriver(options); d.manage().window().maximize(); d.manage().timeouts().implicitlyWait(3,TimeUnit.SECONDS); }
/** * Generates a chrome webdriver. * * @param headlessMode * Enable headless mode ? * @return * A chrome webdriver * @throws TechnicalException * if an error occured when Webdriver setExecutable to true. */ private WebDriver generateGoogleChromeDriver(boolean headlessMode) throws TechnicalException { final String pathWebdriver = DriverFactory.getPath(Driver.CHROME); if (!new File(pathWebdriver).setExecutable(true)) { throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE)); } logger.info("Generating Chrome driver ({}) ...",pathWebdriver); System.setProperty(Driver.CHROME.getDriverName(),pathWebdriver); final ChromeOptions chromeOptions = new ChromeOptions(); final DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION,true); capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIoUR,UnexpecteDalertBehavIoUr.ACCEPT); setLoggingLevel(capabilities); if (Context.isHeadless()) { chromeOptions.addArguments("--headless"); } // Proxy configuration if (Context.getProxy().getProxyType() != ProxyType.UNSPECIFIED && Context.getProxy().getProxyType() != ProxyType.AUTODETECT) { capabilities.setCapability(CapabilityType.PROXY,Context.getProxy()); } setChromeOptions(capabilities,chromeOptions); String withWhitelistedIps = Context.getWebdriversProperties("withWhitelistedIps"); if (withWhitelistedIps != null && !"".equals(withWhitelistedIps)) { ChromeDriverService service = new ChromeDriverService.Builder().withWhitelistedIps(withWhitelistedIps).withVerbose(false).build(); return new ChromeDriver(service,capabilities); } else { return new ChromeDriver(capabilities); } }
@Before public void start() { driver = new ChromeDriver(); //driver = new FirefoxDriver(); //driver = new InternetExplorerDriver(); wait = new webdriverwait(driver,10); }
public static WebDriver getDriverUsingMatcherAndCommonFunctions() { return Match(System.getProperty("browser")).of( Case(anyOf(isNull(),String::isEmpty),() -> { throw new IllegalStateException("'browser' property is missing!"); }),Case(CHROME::equalsIgnoreCase,() -> new ChromeDriver()),Case(FIREFOX::equalsIgnoreCase,() -> new FirefoxDriver()),Case($(),browser -> { throw new IllegalArgumentException(browser + " browser is not supported!"); })); }
@Before public void start() { /* // Collect login data before start Scanner in = new Scanner(system.in); System.out.println ("Enter login: "); email = in.nextLine(); System.out.println ("Enter password: "); psw = in.nextLine(); */ //open new window driver = new ChromeDriver(); wait = new webdriverwait(driver,10); }
@Before public void start() { driver = new ChromeDriver(); //driver = new FirefoxDriver(); //driver = new InternetExplorerDriver(); wait = new webdriverwait(driver,10); }
static void test() { System.setProperty("webdriver.chrome.driver","D:\\selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(3,TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(5,TimeUnit.SECONDS); String url = "http://www.baidu.com/"; driver.get(url); //��ȡ��ǰҳ��ȫ��iframe������iframe����Ԫ�� try { List<WebElement> iframes = driver.findElements(By.tagName("iframe")); //��ȡȫ��iframe��ǩ if(iframes.size()!=0) { for(WebElement iframe : iframes) { if(iframe.getSize() != null) { System.out.println(iframe.getAttribute("outerHtml")); } } }else{ System.out.println("��ҳ�治����iframe"); } }catch(Exception e) { System.out.println(e); } }
public WebDriver maximizebrowserAndDrivers() { String chromePath = System.getProperty("user.dir") + "/Drivers/chrome/chromedriver"; System.setProperty("webdriver.chrome.driver",chromePath); ChromeOptions options = new ChromeOptions(); options.addArguments("--incognito"); this.driver = new ChromeDriver(); driver.manage().window().maximize(); return driver; }
@Test public void callsTheCorrectConstructor() throws Exception { ChromeDriverService chromeDriverService = mock(ChromeDriverService.class); DesiredCapabilities desiredCapabilities = mock(DesiredCapabilities.class); ChromeDriver expected = mock(ChromeDriver.class); whenNew(ChromeDriver.class).withArguments(chromeDriverService,desiredCapabilities).thenReturn(expected); ChromeDriversupplier chromeDriversupplier = new ChromeDriversupplier(); WebDriver actual = chromeDriversupplier.get(chromeDriverService,desiredCapabilities); assertEquals(expected,actual); }
public static WebDriver getDriverUsingMatcherAndCustomFunctions(DesiredCapabilities capabilities) { return Match(capabilities).of( Case(isNull(),() -> { throw new IllegalStateException("DesiredCapabilities are missing!"); }),Case(hasNobrowser,() -> { throw new IllegalArgumentException("'browser' capability is missing!"); }),Case(isChrome,caps -> new ChromeDriver(caps)),Case(isFirefox,caps -> new FirefoxDriver(caps)),caps -> { throw new IllegalArgumentException(caps.getbrowserName() + " browser is not supported!"); })); }
@Test void webrtcTest(ChromeDriver driver) { driver.get( "https://webrtc.github.io/samples/src/content/devices/input-output/"); assertthat(driver.findElement(By.id("video")).getTagName(),equalTo("video")); }
public static WebDriver getChromeDriver(String pathtochromeExecutable) { String path = System.getProperty("user.dir") + "\\Drivers\\chromedriver.exe"; System.setProperty("webdriver.chrome.driver",path); Map<String,Object> chromeOptions = new HashMap<String,Object>(); chromeOptions.put("binary",pathtochromeExecutable); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY,chromeOptions); return new ChromeDriver(capabilities); }
@Test void screenshottest(ChromeDriver driver) { driver.get("https://bonigarcia.github.io/selenium-jupiter/"); assertthat(driver.getTitle(),containsstring("A JUnit 5 extension for Selenium WebDriver")); imageFile = new File("screenshottest_arg0_ChromeDriver_" + driver.getSessionId() + ".png"); }
@Test void screenshottest(ChromeDriver driver) { driver.get("https://bonigarcia.github.io/selenium-jupiter/"); assertthat(driver.getTitle(),containsstring("A JUnit 5 extension for Selenium WebDriver")); imageFile = new File("screenshottest_arg0_ChromeDriver_" + driver.getSessionId() + ".png"); }
@Test void screenshottest(ChromeDriver driver) { driver.get("https://bonigarcia.github.io/selenium-jupiter/"); assertthat(driver.getTitle(),containsstring("A JUnit 5 extension for Selenium WebDriver")); imageName = new File( "./target/surefire-reports/io.github.bonigarcia.test.screenshot.ScreenshotSurefireTest","screenshottest_arg0_ChromeDriver_" + driver.getSessionId() + ".png"); }
private void updateTt(Consumer<Tt> onTtUpsert,Consumer<TtResult> onTtResultUpsert,ChromeDriver driver,Tt tt) { tt.setUrl(String.format("%s%d/","https://www.facebook.com/groups/first4figures/permalink/",tt.getId())); driver.get(tt.getUrl()); WebElement timestampElement = driver.findElementByCssSelector(String.format("a[href*='%s']>[data-utime]",tt.getId())); List<WebElement> values = driver.findElementsByCssSelector("a[data-tooltip-content$='other people']"); List<WebElement> category = driver.findElementsByCssSelector("div[role='presentation']>div:nth-child(2)>span"); if (timestampElement != null) { Long timestamp = Long.parseLong(timestampElement.getAttribute("data-utime")); tt.setCreationDate(timestamp); } if (values.size() < 2 || category.size() < 2) { throw new RuntimeException("Couldn't parse TT from page: " + tt); } TtResult ttResult = new TtResult(UUID.randomUUID().toString(),tt.getId(),Instant.Now().getEpochSecond()); for (int i = 0; i < 2; i++) { Matcher matcher = Pattern.compile("-?\\d+").matcher(values.get(i).getAttribute("data-tooltip-content")); if (!matcher.find()) { throw new RuntimeException("Couldn't parse TT result from page : " + tt); } String label = category.get(i).getText(); Long value = Long.parseLong(matcher.group()); if ("Yes".equalsIgnoreCase(label)) { ttResult.setYes(value); } else if ("No".equalsIgnoreCase(label)) { ttResult.setNo(value); } } LOGGER.log(Level.INFO,String.format("upsert : %s",tt.toString())); onTtUpsert.accept(tt); LOGGER.log(Level.INFO,ttResult.toString())); onTtResultUpsert.accept(ttResult); }
@Test public void testWithChromeAndFirefox(ChromeDriver driver1,FirefoxDriver driver2) { driver1.get("http://www.seleniumhq.org/"); driver2.get("http://junit.org/junit5/"); assertthat(driver1.getTitle(),startsWith("Selenium")); assertthat(driver2.getTitle(),equalTo("JUnit 5")); }
@disabled("Redudant test for Travis CI suite") // tag::snippet-in-doc[] @Test public void testWithTwoChromes(ChromeDriver driver1,ChromeDriver driver2) { driver1.get("http://www.seleniumhq.org/"); driver2.get("http://junit.org/junit5/"); assertthat(driver1.getTitle(),equalTo("JUnit 5")); }
static Stream<Arguments> forcedTestProvider() { return Stream.of( Arguments.of(AppiumDriverHandler.class,ForcedAppiumJupiterTest.class,AppiumDriver.class,"appiumNoCapabilitiesTest"),Arguments.of(AppiumDriverHandler.class,"appiumWithCapabilitiesTest"),Arguments.of(ChromeDriverHandler.class,ForcedBadChromeJupiterTest.class,ChromeDriver.class,"chromeTest"),Arguments.of(FirefoxDriverHandler.class,ForcedBadFirefoxJupiterTest.class,FirefoxDriver.class,"firefoxTest"),Arguments.of(RemoteDriverHandler.class,ForcedBadRemoteJupiterTest.class,RemoteWebDriver.class,"remoteTest"),Arguments.of(EdgeDriverHandler.class,ForcedEdgeJupiterTest.class,EdgeDriver.class,"edgeTest"),Arguments.of(OperaDriverHandler.class,ForcedOperaJupiterTest.class,OperaDriver.class,"operaTest"),Arguments.of(SafariDriverHandler.class,ForcedSafariJupiterTest.class,SafariDriver.class,"safariTest")); }
/** * {@inheritDoc} */ @Override public ChromeDriver start(Capabilities other) { Capabilities capabilities = this.mergeCapabilities(other); if (capabilities == null) { return new ChromeDriver(); } return new ChromeDriver(capabilities); }
public static WebDriver getChromeDriver() { String path = "src/test/resources/chromedriver"; System.setProperty("webdriver.chrome.driver",path); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability("networkConnectionEnabled",true); capabilities.setCapability("browserConnectionEnabled",true); return new ChromeDriver(capabilities); }
/** * Load the default configuration. It will not erase prevIoUs non-default configurations. * * @return Itself. */ public SeleniumConfiguration loadDefaultConfiguration() { this.getConfiguration().put(ChromeDriver.class,new ChromeConfiguration()); this.getConfiguration().put(EdgeDriver.class,new EdgeConfiguration()); this.getConfiguration().put(FirefoxDriver.class,new FirefoxConfiguration()); this.getConfiguration().put(HtmlUnitConfiguration.class,new HtmlUnitConfiguration()); this.getConfiguration().put(InternetExplorerConfiguration.class,new InternetExplorerConfiguration()); this.getConfiguration().put(OperaConfiguration.class,new OperaConfiguration()); this.getConfiguration().put(PhantomJSConfiguration.class,new PhantomJSConfiguration()); this.getConfiguration().put(SafariDriver.class,new SafariConfiguration()); return this; }
@BeforeClass public static void sharedForAllTests() { // Keep the WebDriver browser window open between tests ChromeOptions co = new ChromeOptions(); co.addArguments("headless"); co.addArguments("window-size=1200x800"); DRIVER = new ChromeDriver(co); FWD = new FluentWebDriver(DRIVER); }
org.openqa.selenium.SessionNotCreatedException的实例源码
public void failsWhenRequestingNonCurrentPlatform() throws Throwable { Platform[] values = Platform.values(); Platform otherPlatform = null; for (Platform platform : values) { if (Platform.getCurrent().is(platform)) { continue; } otherPlatform = platform; break; } DesiredCapabilities caps = new DesiredCapabilities("java","1.0",otherPlatform); try { driver = new JavaDriver(caps,caps); throw new MissingException(SessionNotCreatedException.class); } catch (SessionNotCreatedException e) { } }
private ServerSideSession safeStart(DesiredCapabilities cap) { ServerSideSession session = null; try { // init session session = getServer().createSession(cap); if (session == null) { throw new SessionNotCreatedException( "The server is currently shutting down and doesn't accept new tests."); } // start session session.start(); return session; } catch (Exception e) { // Todo(user): Clean this up to meet logging best practices (should not log and throw). logger.atSevere().withCause(e).log("Error starting the session"); if (session != null) { session.stop(); } throw new SessionNotCreatedException(e.getMessage(),e); } }
public SeleniumHelper getSeleniumHelper() { if (helper == null) { DriverFactory currentFactory = getFactory(); if (currentFactory == null) { throw new StopTestException("Cannot use Selenium before configuring how to start a driver (for instance using SeleniumDriverSetup)"); } else { try { WebDriver driver = currentFactory.createDriver(); postProcessDriver(driver); SeleniumHelper newHelper = createHelper(driver); newHelper.setWebDriver(driver,getDefaultTimeoutSeconds()); setSeleniumHelper(newHelper); } catch (SessionNotCreatedException e) { throw new StopTestException("Unable to create selenium session using: " + currentFactory,e); } } } return helper; }
public void failsWhenRequestingANonJavaDriver() throws Throwable { DesiredCapabilities caps = new DesiredCapabilities("xjava",Platform.getCurrent()); try { driver = new JavaDriver(caps,caps); throw new MissingException(SessionNotCreatedException.class); } catch (SessionNotCreatedException e) { } }
public void failsWhenRequestingUnsupportedCapability() throws Throwable { DesiredCapabilities caps = new DesiredCapabilities("java",Platform.getCurrent()); caps.setCapability("rotatable",true); try { driver = new JavaDriver(caps,caps); throw new MissingException(SessionNotCreatedException.class); } catch (SessionNotCreatedException e) { } }
@Override public Response handle() throws Exception { ServerSideSession session = null; try { JsonObject capsJson = getRequest().getPayload().getJsonObject("desiredCapabilities"); session = safeStart(new DesiredCapabilities(JavaxJson.toJavaMap(capsJson))); if (session == null) { throw new SessionNotCreatedException("Failed to start session."); } Response r = new Response(); r.setSessionId(session.getSessionId()); r.setValue(session.getWebDriver().capabilities()); r.setStatus(0); return r; } catch (Exception e) { logger.atSevere().withCause(e).log(); if (session != null) { session.stop(); } if (e instanceof WebDriverException) { throw e; } else { throw new SessionNotCreatedException(e.getMessage(),e); } } }
今天的关于org.openqa.selenium.SessionNotCreatedException:未创建会话:此版本的ChromeDriver仅支持使用Selenium的Chrome版本75的分享已经结束,谢谢您的关注,如果想了解更多关于java – Selenium 3.0 Firefx驱动程序失败与org.openqa.selenium.SessionNotCreatedException无法创建新的远程会话、org.openqa.selenium.chrome.ChromeDriverService的实例源码、org.openqa.selenium.chrome.ChromeDriver的实例源码、org.openqa.selenium.SessionNotCreatedException的实例源码的相关知识,请在本站进行查询。
本文标签: