org.openqa.selenium.chrome.ChromeDriver Java Examples

The following examples show how to use org.openqa.selenium.chrome.ChromeDriver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReportLayoutTests.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void init(){
	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
	driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
	try{
		driver.get("http://localhost:8080/q2r/login.html");
		Thread.sleep(1000);
		driver.findElement(By.id("username")).sendKeys("admin");
		driver.findElement(By.id("password")).sendKeys("admin");
		driver.findElement(By.id("loginButton")).click();
		Thread.sleep(1000);
	}catch(Exception e){
		e.printStackTrace();
	}
}
 
Example #2
Source File: ReportShowCaseDemo.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void init(){
	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
	driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
	try{
		driver.get("http://localhost:8080/q2r/login.html");
		Thread.sleep(1000);
		driver.findElement(By.id("username")).sendKeys("admin");
		driver.findElement(By.id("password")).sendKeys("admin");
		driver.findElement(By.id("loginButton")).click();
		Thread.sleep(1000);
	}catch(Exception e){
		e.printStackTrace();
	}
}
 
Example #3
Source File: ForcedAnnotationReaderTest.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
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(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"));
}
 
Example #4
Source File: SeleniumDriverHandler.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static WebDriver getChromeDriver() {

        /*
            Need to have Chrome (eg version 53.x) and the Chrome Driver (eg 2.24),
            whose executable should be saved directly under your home directory

            see https://sites.google.com/a/chromium.org/chromedriver/getting-started
         */

        boolean isOk = setupDriverExecutable("chromedriver", "webdriver.chrome.driver");
        if(! isOk){
            return null;
        }

        return new ChromeDriver();
    }
 
Example #5
Source File: RegisteringMultipleListeners.java    From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License 6 votes vote down vote up
public static void main(String... args){

        System.setProperty("webdriver.chrome.driver",
                "./src/test/resources/drivers/chromedriver");

        WebDriver driver = new ChromeDriver();

        try {
            EventFiringWebDriver eventFiringDriver = new
                    EventFiringWebDriver(driver);
            IAmTheEventListener eventListener = new IAmTheEventListener();
            IAmTheEventListener2 eventListener2 = new
                    IAmTheEventListener2();
            eventFiringDriver.register(eventListener);
            eventFiringDriver.register(eventListener2);
            eventFiringDriver.get("http://www.google.com");
            eventFiringDriver.get("http://www.facebook.com");
            eventFiringDriver.navigate().back();
        } finally {
            driver.close();
            driver.quit();
        }
    }
 
Example #6
Source File: IAmTheDriver.java    From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License 6 votes vote down vote up
public static void main(String... args){

        System.setProperty("webdriver.chrome.driver",
                "./src/test/resources/drivers/chromedriver");

        WebDriver driver = new ChromeDriver();

        try {
            EventFiringWebDriver eventFiringDriver = new
                    EventFiringWebDriver(driver);
            IAmTheEventListener eventListener = new IAmTheEventListener();
            eventFiringDriver.register(eventListener);
            eventFiringDriver.get("http://www.google.com");
            eventFiringDriver.get("http://www.facebook.com");
            eventFiringDriver.navigate().back();
        } finally {
            driver.close();
            driver.quit();
        }
    }
 
Example #7
Source File: Utils.java    From PicCrawler with Apache License 2.0 6 votes vote down vote up
/**
 * 对当前对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();
}
 
Example #8
Source File: SetupConfiguration.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
@BeforeClass
	public static void init(){
		driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
		driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
//		try {
//		GraphicsConfiguration gc = GraphicsEnvironment
//			      .getLocalGraphicsEnvironment()
//			      .getDefaultScreenDevice()
//			      .getDefaultConfiguration();
//			screenRecorder = new ScreenRecorder(gc);
//			screenRecorder.start();
//			driver.get("http://localhost:8080/q2r/login");
//			Thread.sleep(5000);
//			driver.findElement(By.id("username")).sendKeys("admin");
//			driver.findElement(By.id("password")).sendKeys("admin");
//			driver.findElement(By.id("loginButton")).click();
//			Thread.sleep(5000);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		} 
	}
 
Example #9
Source File: LocalExecutionTest.java    From demo-java with MIT License 6 votes vote down vote up
@Test
public void localExecution() {
    // Options:
    //
    // 1. Specify location of driver
    // System.setProperty("webdriver.chrome.driver", "lib/drivers/chromedriver");
    //
    // 2. Add driver to PATH ENV
    //
    // 3. Use Driver manager:
    WebDriverManager.chromedriver().setup();

    // Start session (opens browser)
    WebDriver driver = new ChromeDriver();

    // Quit session (closes browser)
    driver.quit();
}
 
Example #10
Source File: SalesDemo.java    From query2report with GNU General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void init(){
	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
	driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
	try{
		driver.get("http://localhost:8080/q2r/login.html");
		Thread.sleep(1000);
		driver.findElement(By.id("username")).sendKeys("admin");
		driver.findElement(By.id("password")).sendKeys("admin");
		driver.findElement(By.id("loginButton")).click();
		Thread.sleep(1000);
	}catch(Exception e){
		e.printStackTrace();
	}
}
 
Example #11
Source File: DriverFactory.java    From qa-automation-samples with MIT License 6 votes vote down vote up
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();
}
 
Example #12
Source File: ChromeDriverHandler.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
@Override
public void resolve() {
    try {
        Optional<Object> testInstance = context.getTestInstance();
        Optional<Capabilities> capabilities = annotationsReader
                .getCapabilities(parameter, testInstance);
        ChromeOptions chromeOptions = (ChromeOptions) getOptions(parameter,
                testInstance);

        if (chromeOptions.asMap().get(CAPABILITY).toString().toLowerCase()
                .contains("chromium")) {
            WebDriverManager.chromiumdriver().setup();
        }

        if (capabilities.isPresent()) {
            chromeOptions.merge(capabilities.get());
        }

        object = new ChromeDriver(chromeOptions);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example #13
Source File: Shadow.java    From shadow-automation-selenium with Apache License 2.0 6 votes vote down vote up
public Shadow(WebDriver driver) {
	
	if (driver instanceof ChromeDriver) {
		sessionId  = ((ChromeDriver)driver).getSessionId();
		chromeDriver = (ChromeDriver)driver;
	} else if (driver instanceof FirefoxDriver) {
		sessionId  = ((FirefoxDriver)driver).getSessionId();
		firfoxDriver = (FirefoxDriver)driver;
	} else if (driver instanceof InternetExplorerDriver) {
		sessionId  = ((InternetExplorerDriver)driver).getSessionId();
		ieDriver = (InternetExplorerDriver)driver;
	} else if (driver instanceof RemoteWebDriver) {
		sessionId  = ((RemoteWebDriver)driver).getSessionId();
		remoteWebDriver = (RemoteWebDriver)driver;
	} 
	this.driver = driver;
}
 
Example #14
Source File: HtmlFileInputTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void contentType(final String extension) throws Exception {
    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload1", Upload1Servlet.class);
    servlets.put("/upload2", ContentTypeUpload2Servlet.class);
    startWebServer("./", new String[0], servlets);

    final WebDriver driver = getWebDriver();
    driver.get(URL_FIRST + "upload1");

    final File tmpFile = File.createTempFile("htmlunit-test", "." + extension);
    try {
        String path = tmpFile.getAbsolutePath();
        if (driver instanceof InternetExplorerDriver || driver instanceof ChromeDriver) {
            path = path.substring(path.indexOf('/') + 1).replace('/', '\\');
        }
        driver.findElement(By.name("myInput")).sendKeys(path);
        driver.findElement(By.id("mySubmit")).click();
    }
    finally {
        assertTrue(tmpFile.delete());
    }

    final String pageSource = driver.getPageSource();
    assertTrue(pageSource, pageSource.contains(getExpectedAlerts()[0]));
    assertFalse(pageSource, pageSource.contains(getExpectedAlerts()[1]));
}
 
Example #15
Source File: HealTurnedOffTest.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: UserMgmtChangeAdminPwdTest.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void init(){
	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
	driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
}
 
Example #17
Source File: ChromeDriverConfigTest.java    From jmeter-plugins-webdriver with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotStopServiceIfNotRunningWhenQuitBrowserIsInvoked() throws Exception {
    ChromeDriver mockChromeDriver = mock(ChromeDriver.class);
    ChromeDriverService mockService = mock(ChromeDriverService.class);
    when(mockService.isRunning()).thenReturn(false);
    config.getServices().put(config.currentThreadName(), mockService);

    config.quitBrowser(mockChromeDriver);

    verify(mockChromeDriver).quit();
    assertThat(config.getServices(), is(Collections.<String, ChromeDriverService>emptyMap()));
    verify(mockService, times(0)).stop();
}
 
Example #18
Source File: ChromeWithGlobalOptionsJupiterTest.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #19
Source File: SeleniumTestUtilities.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
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);
}
 
Example #20
Source File: ActionsTest.java    From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License 5 votes vote down vote up
@BeforeMethod
public void setup() throws IOException {

    System.setProperty("webdriver.chrome.driver",
            "./src/test/resources/drivers/chromedriver");
    driver = new ChromeDriver();
}
 
Example #21
Source File: CustomDriverProvider.java    From akita with Apache License 2.0 5 votes vote down vote up
@Override
public WebDriver createDriver(DesiredCapabilities capabilities) {
    Configuration.browserSize = String.format("%sx%s", loadSystemPropertyOrDefault(WINDOW_WIDTH, DEFAULT_WIDTH),
            loadSystemPropertyOrDefault(WINDOW_HEIGHT, DEFAULT_HEIGHT));
    String expectedBrowser = loadSystemPropertyOrDefault(BROWSER, CHROME);
    String remoteUrl = loadSystemPropertyOrDefault(REMOTE_URL, LOCAL);
    BlackList blackList = new BlackList();
    boolean isProxyMode = loadSystemPropertyOrDefault(PROXY, false);
    if (isProxyMode) {
        enableProxy(capabilities);
    }

    log.info("remoteUrl=" + remoteUrl + " expectedBrowser= " + expectedBrowser + " BROWSER_VERSION=" + System.getProperty(CapabilityType.BROWSER_VERSION));

    switch (expectedBrowser.toLowerCase()) {
        case (FIREFOX):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createFirefoxDriver(capabilities) : getRemoteDriver(getFirefoxDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (MOBILE_DRIVER):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? new ChromeDriver(getMobileChromeOptions(capabilities)) : getRemoteDriver(getMobileChromeOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (OPERA):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createOperaDriver(capabilities) : getRemoteDriver(getOperaRemoteDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (SAFARI):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createSafariDriver(capabilities) : getRemoteDriver(getSafariDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (INTERNET_EXPLORER):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createIEDriver(capabilities) : getRemoteDriver(getIEDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (IE):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createIEDriver(capabilities) : getRemoteDriver(getIEDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        case (EDGE):
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createEdgeDriver(capabilities) : getRemoteDriver(getEdgeDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());
        default:
            return LOCAL.equalsIgnoreCase(remoteUrl) ? createChromeDriver(capabilities) : getRemoteDriver(getChromeDriverOptions(capabilities), remoteUrl, blackList.getBlacklistEntries());

    }
}
 
Example #22
Source File: ScreenshotBase64Test.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@Test
void screenshotTest(ChromeDriver driver) {
    driver.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver.getTitle(),
            containsString("JUnit 5 extension for Selenium"));

    imageFile = new File("screenshotTest_arg0_ChromeDriver_"
            + driver.getSessionId() + ".png");
}
 
Example #23
Source File: RegistrationAndAuthenticationE2ETest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: ITCreateBucket.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    baseUrl = "http://localhost:18080/nifi-registry";
    wait = new WebDriverWait(driver, 30);
}
 
Example #25
Source File: UserMgmtNewUserTest.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void init(){
	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
	driver.manage().timeouts().pageLoadTimeout(30,TimeUnit.SECONDS);
}
 
Example #26
Source File: ChromeDriverConfig.java    From jmeter-plugins-webdriver with Apache License 2.0 5 votes vote down vote up
@Override
protected ChromeDriver createBrowser() {
    final ChromeDriverService service = getThreadService();
    return service != null ? new ChromeDriver(service, createCapabilities()) : null;
}
 
Example #27
Source File: ChromeJupiterTest.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
@Test
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"));
}
 
Example #28
Source File: SeleniumTestUtilities.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
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);
}
 
Example #29
Source File: SeleniumTestUtilities.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
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);
}
 
Example #30
Source File: HTMLFormElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure that text/plain form parameters are correctly encoded.
 * @throws Exception if the test fails
 */
@Test
@Alerts({"application/x-www-form-urlencoded", "myFile=htmlunit-test", ".txt"})
public void submitUrlEncodedFile() throws Exception {
    final String html = "<html>\n"
            + "<body>\n"
            + "  <form action='foo.html' enctype='application/x-www-form-urlencoded' method='post'>\n"
            + "    <input type='file' id='f' name='myFile'>\n"
            + "    <input id='clickMe' type='submit' value='Click Me'>\n"
            + "  </form>\n"
            + "</body>\n"
            + "</html>";

    getMockWebConnection().setDefaultResponse("");

    final WebDriver driver = loadPage2(html);

    final File tmpFile = File.createTempFile("htmlunit-test", ".txt");
    try {
        String path = tmpFile.getAbsolutePath();
        if (driver instanceof InternetExplorerDriver || driver instanceof ChromeDriver) {
            path = path.substring(path.indexOf('/') + 1).replace('/', '\\');
        }
        driver.findElement(By.id("f")).sendKeys(path);
        driver.findElement(By.id("clickMe")).click();
    }
    finally {
        assertTrue(tmpFile.delete());
    }

    final String headerContentType = getMockWebConnection().getLastWebRequest().getAdditionalHeaders()
            .get(HttpHeader.CONTENT_TYPE);
    assertEquals(getExpectedAlerts()[0], headerContentType);

    final String body = getMockWebConnection().getLastWebRequest()
            .getRequestParameters().get(0).toString();
    assertTrue(body, body.startsWith(getExpectedAlerts()[1]));
    assertTrue(body, body.endsWith(getExpectedAlerts()[2]));
    assertNull(getMockWebConnection().getLastWebRequest().getRequestBody());
}