Java Code Examples for org.openqa.selenium.WebDriver#close()
The following examples show how to use
org.openqa.selenium.WebDriver#close() .
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: PageSteps.java From vividus with Apache License 2.0 | 7 votes |
/** * Closes <b>current window</b> and switches to the window from which rederection to current window was performed * <p> * Each browser <b>window</b> or <b>tab</b> is considered to be a separate <b>window object</b>. This object holds * corresponding <b>Document</b> object, which itself is a html page. So this method applies to both windows and * tabs. * <p> * Actions performed at this step: * <ul> * <li>Receives all opened browser windows * <li>Identifies current window and closes it * <li>Switches back to the window from which rederection to current window was performed * </ul> * @see <a href="https://html.spec.whatwg.org/#browsing-context"><i>Browsing context (Window & Document)</i></a> * @see <a href="https://www.w3schools.com/tags/default.asp"><i>HTML Element Reference</i></a> */ @When("I close the current window") public void closeCurrentWindow() { WebDriver driver = getWebDriver(); String currentWindow = driver.getWindowHandle(); for (String window : driver.getWindowHandles()) { if (!window.equals(currentWindow)) { driver.close(); driver.switchTo().window(window); break; } } highlightingSoftAssert.assertThat("Current window has been closed", String.format("Current window '%s' has been closed", currentWindow), driver.getWindowHandles(), not(contains(currentWindow))); }
Example 2
Source File: TabAndWindowStepDefinition.java From IridiumApplicationTesting with MIT License | 6 votes |
/** * Switchs to the specified window. This is useful when you open a link that opens in a new * window. * @param ignoreErrors ignore any errors */ @When("I close the current window( ignoring errors)?") public void closeWindow(final String ignoreErrors) { try { final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread(); /* Close the current window */ webDriver.close(); /* Switch to another window (otherwise all other commands fail) */ if (webDriver.getWindowHandles().iterator().hasNext()) { webDriver.switchTo().window(webDriver.getWindowHandles().iterator().next()); } else { throw new BrowserWindowException("You can only use this step when there is more than one tab or window."); } sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep()); } catch (final Exception ex) { if (StringUtils.isBlank(ignoreErrors)) { throw ex; } } }
Example 3
Source File: BrowserTest.java From hsac-fitnesse-fixtures with Apache License 2.0 | 6 votes |
public boolean closeTab() { boolean result = false; List<String> tabs = getTabHandles(); int currentTab = getCurrentTabIndex(tabs); int tabToGoTo = -1; if (currentTab > 0) { tabToGoTo = currentTab - 1; } else { if (tabs.size() > 1) { tabToGoTo = 1; } } if (tabToGoTo > -1) { WebDriver driver = driver(); driver.close(); goToTab(tabs, tabToGoTo); result = true; } return result; }
Example 4
Source File: EngineInvoker.java From phoenix.webui.framework with Apache License 2.0 | 6 votes |
/** * 关闭url以指定字符串开头的window * @param phoenix 引擎 * @param params 参数 */ public static void closeWinByUrlStartWith(Phoenix phoenix, String[] params) { String startWith = params[0]; WebDriver driver = phoenix.getEngine().getDriver(); Set<String> handles = driver.getWindowHandles(); Iterator<String> handleIt = handles.iterator(); String currentHandle = driver.getWindowHandle(); while(handleIt.hasNext()) { String handle = handleIt.next(); driver.switchTo().window(handle); if(driver.getCurrentUrl().startsWith(startWith)) { driver.close(); break; } } driver.switchTo().window(currentHandle); }
Example 5
Source File: WebPage.java From phoenix.webui.framework with Apache License 2.0 | 6 votes |
@Override public void closeOthers() { String currentTitle = getTitle(); String currentWinHandle = engine.getDriver().getWindowHandle(); for(String winHandle : engine.getDriver().getWindowHandles()) { WebDriver itemDrive = engine.getDriver().switchTo().window(winHandle); if(!itemDrive.getTitle().equals(currentTitle)) { itemDrive.close(); } } engine.getDriver().switchTo().window(currentWinHandle); }
Example 6
Source File: RegisteringMultipleListeners.java From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License | 6 votes |
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 7
Source File: IAmTheDriver.java From Selenium-WebDriver-3-Practical-Guide-Second-Edition with MIT License | 6 votes |
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 8
Source File: DefaultSession.java From selenium with Apache License 2.0 | 6 votes |
@Override public void close() { try { WebDriver driver = getDriver(); if (driver != null) { driver.close(); } } catch (RuntimeException e) { // At least we tried. } if (tempFs != null) { tempFs.deleteTemporaryFiles(); tempFs.deleteBaseDir(); tempFs = null; } }
Example 9
Source File: DriverFactory.java From NoraUi with GNU Affero General Public License v3.0 | 5 votes |
/** * Clear loaded drivers */ public void clear() { for (final WebDriver wd : drivers.values()) { wd.manage().deleteAllCookies(); while (wd.getWindowHandles().size() > 1) { wd.close(); } wd.get("data:,"); } }
Example 10
Source File: GitCrawler.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
public static void main(String[] args) { WebDriver driver = SeleniumDriverHandler.getChromeDriver(); try { crawl(driver); } catch (Exception e){ System.out.println("ERROR: "+e.getMessage()); e.printStackTrace(); } driver.close(); }
Example 11
Source File: FirstFirefoxTest.java From webDriverExperiments with MIT License | 5 votes |
@Test /* * Physical browsers have to be closed, otherwise you will * have a bunch of browsers open on your screen. * * .close to close single window and browser if it is the last window * .quit to close browser and all windows */ public void firefoxIsSupportedByWebDriver(){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.compendiumdev.co.uk/selenium"); assertTrue(driver.getTitle().startsWith( "Selenium Simplified")); driver.close(); // for early version combinations of Firefox and WebDriver we didn't need // .quit - I have added this line for the combination of WebDriver 2.31.0 // and Firefox 20. According to the API we should not need to do a .quit // after a .close if there was only 1 window open. But sometimes the browser // version advances ahead of the WebDriver version and minor incompatibilities // happen. // Added the line below because of incompatibilite between 2.31.0 and Firefox 20 // where a single window browser does not close when run from the IDE. driver.quit(); }
Example 12
Source File: LocalDriver.java From blueocean-plugin with MIT License | 5 votes |
public static void destroy() { WebDriver driver = CURRENT_WEB_DRIVER.get(); if (driver != null) { try { driver.quit(); driver.close(); } catch(Exception e) { // ignore, this happens when running individual tests sometimes } } }
Example 13
Source File: LocalDriver.java From blueocean-plugin with MIT License | 5 votes |
@Override public void close() { WebDriver driver = getDriver(); if (driver != null) { try { driver.close(); } catch(Exception e) { // ignore, this happens when running individual tests sometimes } } }
Example 14
Source File: GitCrawler.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
public static void main(String[] args) { WebDriver driver = SeleniumDriverHandler.getChromeDriver(); try { crawl(driver); } catch (Exception e){ System.out.println("ERROR: "+e.getMessage()); e.printStackTrace(); } driver.close(); }
Example 15
Source File: GeckoDriverExample.java From journaldev with MIT License | 5 votes |
public static void main(String[] args) { //specify the location of GeckoDriver for Firefox browser automation System.setProperty("webdriver.gecko.driver", "geckodriver"); WebDriver driver = new FirefoxDriver(); driver.get("https://journaldev.com"); String PageTitle = driver.getTitle(); System.out.println("Page Title is:" + PageTitle); driver.close(); }
Example 16
Source File: UserLogin.java From appengine-tck with Apache License 2.0 | 4 votes |
public void login(@Observes EventContext<Before> event) throws Exception { Before before = event.getEvent(); UserIsLoggedIn userIsLoggedIn = null; if (before.getTestMethod().isAnnotationPresent(UserIsLoggedIn.class)) { userIsLoggedIn = before.getTestMethod().getAnnotation(UserIsLoggedIn.class); } else if (before.getTestClass().isAnnotationPresent(UserIsLoggedIn.class)) { userIsLoggedIn = before.getTestClass().getAnnotation(UserIsLoggedIn.class); } if (userIsLoggedIn != null) { final LoginContext context = new UserLoginContext(userIsLoggedIn); log.info(String.format("Found @UserIsLoggedIn: %s [%s]", context.getEmail(), userIsLoggedIn.location())); final URI baseUri = getBaseURI(before.getTestMethod()); final WebDriver driver = createWebDriver(); try { driver.manage().deleteAllCookies(); driver.navigate().to(baseUri + USER_LOGIN_SERVLET_PATH + "?location=" + URLEncoder.encode(userIsLoggedIn.location(), "UTF-8")); // did we navigate to this requested page, or did we get redirected/forwarded to login already List<WebElement> loginUrlElts = driver.findElements(By.id("login-url")); if (loginUrlElts.size() > 0) { String loginURL = loginUrlElts.get(0).getText(); // check if (isInternalLink(loginURL)) { loginURL = baseUri + loginURL; } // go-to login page driver.navigate().to(loginURL); } // find custom login handler, if exists LoginHandler loginHandler = TestBase.instance(getClass(), LoginHandler.class); if (loginHandler == null) { loginHandler = new DefaultLoginHandler(); } loginHandler.login(driver, context); log.info("Logged-in: " + context.getEmail()); // copy cookies Set<Cookie> cookies = driver.manage().getCookies(); for (Cookie cookie : cookies) { ModulesApi.addCookie(cookie.getName(), cookie.getValue()); } } finally { driver.close(); } } event.proceed(); }
Example 17
Source File: ATHJUnitRunner.java From blueocean-plugin with MIT License | 4 votes |
@Override protected Statement methodInvoker(FrameworkMethod method, Object test) { Statement next = super.methodInvoker(method, test); return new Statement() { @Override public void evaluate() throws Throwable { LoginPage loginPage = injector.getInstance(LoginPage.class); Login methodLogin = method.getAnnotation(Login.class); // determine whether test should login first or not // first check test method, then walk up hierarchy at class level only if(methodLogin != null ) { if(!methodLogin.disable()) { loginPage.login(); } } else { Class<?> clazz = test.getClass(); while (clazz != null) { Login classLogin = clazz.getAnnotation(Login.class); if (classLogin != null) { if (!classLogin.disable()) { loginPage.login(); } break; } clazz = clazz.getSuperclass(); } } try { if (LocalDriver.isSauceLabsMode()) { logger.info("SauceOnDemandSessionID=" + ((RemoteWebDriver) LocalDriver.getDriver()).getSessionId().toString()); } next.evaluate(); outputConsoleLogs(); LocalDriver.executeSauce("job-result=passed"); } catch (Exception e) { LocalDriver.executeSauce("job-result=failed"); writeScreenShotCause(e, test, method); outputConsoleLogs(); throw e; } WebDriver driver = injector.getInstance(WebDriver.class); driver.close(); driver.quit(); } }; }
Example 18
Source File: StepImplementation.java From gauge-gradle-plugin with GNU General Public License v3.0 | 4 votes |
@Step("Say <greeting> to <product name>") public void helloWorld(String greeting, String name) { WebDriver driver = new HtmlUnitDriver(); driver.close(); System.out.println(greeting + ", " + name); }
Example 19
Source File: Close.java From selenium with Apache License 2.0 | 4 votes |
@Override protected Void handleSeleneseCommand(WebDriver driver, String ignored, String alsoIgnored) { driver.close(); return null; }
Example 20
Source File: Toutiao.java From HtmlExtractor with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception{ //等待数据加载的时间 //为了防止服务器封锁,这里的时间要模拟人的行为,随机且不能太短 long waitLoadBaseTime = 3000; int waitLoadRandomTime = 3000; Random random = new Random(System.currentTimeMillis()); //火狐浏览器 WebDriver driver = new FirefoxDriver(); //要抓取的网页 driver.get("http://toutiao.com/"); //等待页面动态加载完毕 Thread.sleep(waitLoadBaseTime+random.nextInt(waitLoadRandomTime)); //要加载多少页数据 int pages=5; for(int i=0; i<pages; i++) { //滚动加载下一页 driver.findElement(By.className("loadmore")).click(); //等待页面动态加载完毕 Thread.sleep(waitLoadBaseTime+random.nextInt(waitLoadRandomTime)); } //输出内容 //找到标题元素 List<WebElement> elements = driver.findElements(By.className("title")); int j=1; for(int i=0;i<elements.size();i++) { try { WebElement element = elements.get(i).findElement(By.tagName("a")); //输出标题 System.out.println((j++) + "、" + element.getText() + " " + element.getAttribute("href")); }catch (Exception e){ System.out.println("ignore "+elements.get(i).getText()+" because "+e.getMessage()); } } //关闭浏览器 driver.close(); }