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); }
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)), Case($(), 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")); 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, String.format("upsert : %s", 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(), startsWith("Selenium")); assertThat(driver2.getTitle(), equalTo("JUnit 5")); }
static Stream<Arguments> forcedTestProvider() { return Stream.of( Arguments.of(AppiumDriverHandler.class, ForcedAppiumJupiterTest.class, AppiumDriver.class, "appiumNoCapabilitiesTest"), Arguments.of(AppiumDriverHandler.class, ForcedAppiumJupiterTest.class, AppiumDriver.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); }