Example usage for org.openqa.selenium WebDriver getPageSource

List of usage examples for org.openqa.selenium WebDriver getPageSource

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver getPageSource.

Prototype

String getPageSource();

Source Link

Document

Get the source of the last loaded page.

Usage

From source file:com.java.AppTestType_18_11_2015.java

public void DRAFTLISTING(WebDriver driver, String fieldText) {

    String fieldType = fieldText;
    String field = fieldText;//  w  w w.  j av a 2 s  .c o  m

    try {
        AppKeyWords cdf = AppKeyWords.valueOf(fieldType.toUpperCase());

        switch (cdf) {

        case EA:
            try {

                driver.findElement(By.cssSelector("a.topLink > span")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//input[@value='Equipment & Accessories']")).click();

                driver.findElement(By.id("chkCustomBuilt")).click();

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                Select industry = new Select(driver.findElement(By.id("select_industry")));
                industry.selectByVisibleText("Vehicles & Buses");

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                Select category = new Select(driver.findElement(By.id("select_category")));
                category.selectByVisibleText("Cars");

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                Select subcategory = new Select(driver.findElement(By.id("select_subcategory")));
                subcategory.selectByVisibleText("Car");

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();

                driver.findElement(By.name("6")).sendKeys("SKODA");

                driver.findElement(By.name("3")).sendKeys("SK4");

                driver.findElement(By.name("2")).sendKeys("2014");

                driver.findElement(By.name("4")).sendKeys("125");

                driver.findElement(By.id("confirm_changes")).click();

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();

                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.findElement(By.id("title")).sendKeys("  " + Time);
                String title = driver.findElement(By.id("title")).getText();

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();

                Thread.sleep(10000);

                driver.findElement(By.linkText("MYONE")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//div[3]/div/div/div/div/div/div/div/ul/li[3]/ul/li/a")).click();
                Thread.sleep(10000);
                driver.findElement(By.xpath("//div[15]/ul/li/a")).click();
                Thread.sleep(10000);

                if (driver.getPageSource().contains(title)) {

                    resultDetails.setFlag(true);
                    System.out.println("listing is displayed");
                }

            } catch (Exception e) {

                e.printStackTrace();
                resultDetails.setFlag(false);
                resultDetails.setErrorMessage("Listing is not displayed in Drafts tab");
            }

            break;

        case COMMERCIAL:

            try {

                driver.findElement(By.cssSelector("a.topLink > span")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//input[@value='Commercial Materials']")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.findElement(By.id("textarea")).sendKeys("Test");

                driver.findElement(By.id("confirm_changes")).click();

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                driver.findElement(By.id("title")).sendKeys(" " + Time);
                String title = driver.findElement(By.id("title")).getText();

                driver.findElement(By.xpath("//input[@value='Save & Continue']")).click();

                Thread.sleep(10000);

                driver.findElement(By.linkText("MYONE")).click();
                Thread.sleep(10000);

                driver.findElement(By.xpath("//div[3]/div/div/div/div/div/div/div/ul/li[3]/ul/li/a")).click();
                Thread.sleep(10000);
                driver.findElement(By.xpath("//div[15]/ul/li/a")).click();
                Thread.sleep(10000);

                if (driver.getPageSource().contains(title)) {

                    resultDetails.setFlag(true);
                    System.out.println("listing is displayed");
                }

            } catch (Exception e) {

                e.printStackTrace();
                resultDetails.setFlag(false);
                resultDetails.setErrorMessage("Listing is not displayed in Drafts tab");
            }

            break;
        }
    } catch (Exception e) {

        resultDetails.setFlag(false);
        resultDetails.setErrorMessage("EA or Commercial listings are not displayed");
    }
}

From source file:com.java.AppTestType_18_11_2015.java

public void SIGNIN(WebDriver driver, String fieldText, String value) {

    try {//www .j a  v a 2  s.  c  om

        try {
            WebDriverWait wait = new WebDriverWait(driver, 20);
            // wait.until(ExpectedConditions.titleIs("Used Equipment Sales | Buy & Sell Online | Ritchie Bros. EquipmentOne"));

            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            driver.manage().deleteAllCookies();
            //driver.findElement(By.linkText("Sign In")).click();
            driver.findElement(By.name("josso_username")).clear();
            driver.findElement(By.name("josso_username")).sendKeys(fieldText);
            driver.findElement(By.name("josso_password")).clear();
            driver.findElement(By.name("josso_password")).sendKeys("Equipment1$");
            try {
                driver.findElement(By.xpath("//*[@value='SIGN IN']")).click();
            } catch (Exception elementnotfoundexException) {
                driver.findElement(By.xpath("//button[text()='SIGN IN']")).click();
            }
            System.out.println("size is   :" + driver.findElements(By.id("iduser")).size());
            if (driver.findElements(By.id("iduser")).size() > 0) {
                System.out.println("1111111111");
                driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
                if (driver.findElements(By.xpath("//input[@id='useragreetoterms' and @type='checkbox']"))
                        .size() > 0) {
                    driver.findElement(By.xpath("//input[@id='useragreetoterms' and @type='checkbox']"))
                            .click();
                    driver.findElement(
                            By.xpath("//*[@class='btn btn-primary btn-group-justified' and @type='submit']"))
                            .click();
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                    // driver.findElement(By.xpath("//input[@value='Go to EquipmentOne']")).click();
                    //  wait.until(ExpectedConditions.titleIs("Used Equipment Sales | Buy & Sell Online | Ritchie Bros. EquipmentOne"));
                }
                //to confirm successful sign in as valid user,verifying the name displayed next to "Hello" text

                if (driver.findElement(By.id("iduser")).getText().equalsIgnoreCase(value))
                    System.out.println("Successfully Logged in");
                else {
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                    driver.findElement(By.linkText("Sign Out")).click();
                    wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.name("josso_password")));
                    driver.findElement(By.name("josso_username")).clear();
                    driver.findElement(By.name("josso_username")).sendKeys(fieldText);
                    driver.findElement(By.name("josso_password")).clear();
                    driver.findElement(By.name("josso_password")).sendKeys("Equipment1$");
                    driver.findElement(By.xpath("//*[@value='SIGN IN']")).click();
                    wait.until(ExpectedConditions.elementToBeClickable(By.id("iduser")));
                    //agree terms-This piece of code is to verify agree terms checkbox after re logging(not logged in as the valid user)
                    driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
                    if (driver.findElements(By.xpath("//input[@id='useragreetoterms' and @type='checkbox']"))
                            .size() > 0) {
                        driver.findElement(By.xpath("//input[@id='useragreetoterms' and @type='checkbox']"))
                                .click();
                        driver.findElement(By
                                .xpath("//*[@class='btn btn-primary btn-group-justified' and @type='submit']"))
                                .click();
                        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                        // driver.findElement(By.xpath("//input[@value='Go to EquipmentOne']")).click();
                        //  wait.until(ExpectedConditions.titleIs("Used Equipment Sales | Buy & Sell Online | Ritchie Bros. EquipmentOne"));
                    }

                }
                resultDetails.setFlag(true);
            }

        }

        //This catch is used to catch the error "You are NOT authorized to access Site" in E1 Login//
        /////////////////////////////////////
        catch (Exception e1) {

            driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
            if (driver.getPageSource().contains("You are NOT authorized to access Site")) {
                System.out.println("You are NOT authorized to access Site error message is displayed");
                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                driver.navigate().to("http://e1.dev.assetnation.com");
                SIGNIN(driver, fieldText, value);
            }

        }
    }

    catch (Exception e) {
        e.printStackTrace();
        resultDetails.setFlag(false);
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void AssetNation(WebDriver driver) {
    try {//from   w w w . j  a  v a2s . c om
        // Actions to be performed on failure

        if (driver.getPageSource().contains("500 Internal server error")) {
            driver.navigate().refresh();
        }
        int userid = driver.findElements(By.id("iduser")).size();
        int logoutlink = driver.findElements(By.linkText("Logout")).size();
        if (userid > 0) {
            SIGNOUT(driver);
            System.out.println("Clicked on Signout after Fail");
        } else if (logoutlink > 0) {
            AMPLOGOUT(driver);
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.mgmtp.jfunk.web.JFunkWebDriverEventListener.java

License:Apache License

/**
 * Saves the currently displayed browser window. The page title is used for the filename -
 * preceded by some identifying information (thread, counter). Pages of the same type are
 * collected inside the same subdirectory. The subdirectory uses
 * {@link SaveOutput#getIdentifier()} for its name. If an alert is present, saving is not
 * supported and thus skipped.//  ww w  .  j  ava  2 s  . com
 *
 * @param action
 *            the event which triggered to save the page. Will be included in the filename.
 * @param triggeredBy
 *            the object which triggered the event (e.g. a button or a link)
 */
protected void savePage(final WebDriver driver, final String action, final String triggeredBy) {
    try {
        // this updates the driver's window handles, so a subsequent call to
        // getWindowHandle() fails if the window no longer exists
        driver.getWindowHandles();
        driver.getWindowHandle();
    } catch (NoSuchWindowException ex) {
        // Window is already closed. Saving the page could cause problems, e. g.
        // ChromeDriver ould hang.
        return;
    }
    File moduleArchiveDir = moduleArchiveDirProvider.get();
    if (moduleArchiveDir == null) {
        return;
    }

    if (config.getBoolean(JFunkConstants.ARCHIVE_DO_NOT_SAVE_WHEN_ALERT, false)) {
        try {
            // Saving the page does not work if an alert is present
            driver.switchTo().alert();
            log.trace("Cannot save page. Alert is present.");
            return;
        } catch (NoAlertPresentException ex) {
            // ignore
        } catch (UnsupportedOperationException ex) {
            // ignore
            // HtmlUnit does not support alerts
        } catch (Exception ex) {
            // ignore
        }
    }

    for (SaveOutput saveOutput : SaveOutput.values()) {
        boolean saveSwitch = saveOutputMap.get(saveOutput);
        if (!saveSwitch) {
            // Saving is disabled by property
            continue;
        }

        File f = null;
        try {
            f = dumpFileCreatorProvider.get().createDumpFile(
                    new File(moduleArchiveDir, saveOutput.getIdentifier()), saveOutput.getExtension(),
                    driver.getCurrentUrl(), action);

            if (f == null) {
                return;
            }

            switch (saveOutput) {
            case HTML:
                StringBuilder html = new StringBuilder();
                html.append("<!-- Requested URL: ");
                html.append(driver.getCurrentUrl());
                html.append(" -->");
                html.append(IOUtils.LINE_SEPARATOR);
                html.append(driver.getPageSource());
                writeStringToFile(f, html.toString(), "UTF-8");
                copyFile(f, new File(moduleArchiveDir, JFunkConstants.LASTPAGE_HTML));
                log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(), action,
                        triggeredBy, driver.getCurrentUrl());
                break;
            case PNG:
                if (driver instanceof TakesScreenshot) {
                    File tmpFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                    if (tmpFile != null) {
                        copyFile(tmpFile, f);
                        log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(),
                                action, triggeredBy, driver.getCurrentUrl());
                        deleteQuietly(tmpFile);
                    }
                }
                break;
            case HTML_VALIDATION:
                /*
                 * JFunkWebDriver.getPageSource() doesn't return the complete page source
                 * e.g. DOCTYPE is missing. Therefore we are using a more complicated way to
                 * retrieve the "real" page source. However, this only works when using
                 * HtmlUnitDriver.
                 */
                if (WebDriverUtils.isHtmlUnitDriver(driver)) {
                    String content = ((HtmlPage) WebDriverUtils.getHtmlUnitDriverWebClient(driver)
                            .getCurrentWindow().getEnclosedPage()).getWebResponse().getContentAsString();
                    writeStringToFile(f, content, "UTF-8");
                    HtmlValidatorUtil.validateHtml(f.getParentFile(), config, f);
                }
                break;
            default:
                throw new IllegalStateException("unknown enum constant");
            }
        } catch (Exception ex) {
            log.error("Could not save file: {}. {}", f, ex.getMessage());
            return;
        }
    }
}

From source file:com.mycompany.webcalculator.OperationsSeleniumTest.java

public void login(WebDriver driver, String siteURL, String username, String password) {

    driver.get(siteURL);/*from  www . j  a  va  2 s  . c  o m*/
    System.out.println(siteURL);
    //wait.until(ExpectedConditions.presenceOfElementLocated(By.id("userid")));
    System.out.println("Loading URL..");

    //extent.log(LogStatus.INFO, "Images", "Image:", imageMap + imageName);
    // takeScreenShot(caseName);

    screenshot.Capture(driver, imageLocation);

    driver.findElement(By.name("em")).clear();
    System.out.println("Waiting for User Id...");
    driver.findElement(By.name("em")).sendKeys(username);
    System.out.println("User Id " + username + " entered.");
    screenshot.Capture(driver, imageLocation);

    //takeScreenShot("test 2");
    driver.findElement(By.name("pw")).clear();
    System.out.println("Waiting for Password...");
    driver.findElement(By.name("pw")).sendKeys(password);
    System.out.println("Password ******* entered.");
    screenshot.Capture(driver, imageLocation);

    //driver.findElement(By.xpath("//button[text()='Submit']")).click();
    driver.findElement(By.name("Login")).click();
    System.out.println("Logging in...");
    screenshot.Capture(driver, imageLocation);

    assertTrue(driver.getPageSource().contains("Invalid login. Please try again"));

}

From source file:com.raja.anucarita.SeCustomActions.java

License:Open Source License

public static boolean seIsTextPresent(WebDriver driver, String TextToCheck) throws Exception {
     String TextFromSite = driver.getPageSource();
     if (TextFromSite.contains(TextToCheck)) {
         result = true;// w w  w  . j  ava2  s .com
     } else {
         result = false;
     }
     //testCaseResult(result,"","",""," Text "+TextToCheck+" Presence Check");
     return result;
 }

From source file:com.technophobia.webdriver.util.ElementLocators.java

License:Open Source License

private static WebElement waitUntil(final WebDriverWait wait, final Function<WebDriver, WebElement> condition,
        WebDriver webDriver) {
    WebElement elem = null;//from   w  ww .j av a2s .co  m
    try {
        elem = wait.until(condition);
    } catch (final TimeoutException e) {

        if (Configuration.INSTANCE.getConfig().getBoolean("log.pagesource.onerror")) {
            LOG.debug("timed out page src:\n" + webDriver.getPageSource());
        }

    }
    return elem;
}

From source file:com.thoughtworks.selenium.webdriven.commands.GetHtmlSource.java

License:Apache License

@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
    return driver.getPageSource();
}

From source file:com.vaadin.testbench.TestBenchDriverTest.java

@Test
public void testTestBenchDriverActsAsProxy() {
    FirefoxDriver mockDriver = createMock(FirefoxDriver.class);
    mockDriver.close();/*from   w ww. j a v  a 2 s.c o  m*/
    expectLastCall().once();
    WebElement mockElement = createNiceMock(WebElement.class);
    expect(mockDriver.findElement(isA(By.class))).andReturn(mockElement);
    List<WebElement> elements = Arrays.asList(mockElement);
    expect(mockDriver.findElements(isA(By.class))).andReturn(elements);
    mockDriver.get("foo");
    expectLastCall().once();
    expect(mockDriver.getCurrentUrl()).andReturn("foo");
    expect(mockDriver.getPageSource()).andReturn("<html></html>");
    expect(mockDriver.getTitle()).andReturn("bar");
    expect(mockDriver.getWindowHandle()).andReturn("baz");
    Set<String> handles = new HashSet<String>();
    expect(mockDriver.getWindowHandles()).andReturn(handles);
    Options mockOptions = createNiceMock(Options.class);
    expect(mockDriver.manage()).andReturn(mockOptions);
    Navigation mockNavigation = createNiceMock(Navigation.class);
    expect(mockDriver.navigate()).andReturn(mockNavigation);
    mockDriver.quit();
    expectLastCall().once();
    expect(((JavascriptExecutor) mockDriver).executeScript(anyObject(String.class))).andStubReturn(true);
    TargetLocator mockTargetLocator = createNiceMock(TargetLocator.class);
    expect(mockDriver.switchTo()).andReturn(mockTargetLocator);
    replay(mockDriver);

    // TestBenchDriverProxy driver = new TestBenchDriverProxy(mockDriver);
    WebDriver driver = TestBench.createDriver(mockDriver);
    driver.close();
    By mockBy = createNiceMock(By.class);
    assertTrue(driver.findElement(mockBy) instanceof TestBenchElementCommands);
    assertTrue(driver.findElements(mockBy).get(0) instanceof TestBenchElementCommands);
    driver.get("foo");
    assertEquals("foo", driver.getCurrentUrl());
    assertEquals("<html></html>", driver.getPageSource());
    assertEquals("bar", driver.getTitle());
    assertEquals("baz", driver.getWindowHandle());
    assertEquals(handles, driver.getWindowHandles());
    assertEquals(mockOptions, driver.manage());
    assertEquals(mockNavigation, driver.navigate());
    driver.quit();
    assertEquals(mockTargetLocator, driver.switchTo());

    verify(mockDriver);
}

From source file:com.vaadin.testbench.util.VersionUtil.java

License:Apache License

private static void initializeVaadinVersion(WebDriver webDriver) {
    Pattern pattern = Pattern.compile("\"vaadinVersion\": ?\"([0-9]+)\\.([0-9]+)\\.([0-9]+)(\\..*)?\"");
    Matcher matcher = pattern.matcher(webDriver.getPageSource());

    if (!matcher.find()) {
        throw new CouldNotParseVaadinVersionException();
    }/*from w ww  . ja v  a2  s. co  m*/

    VAADIN_MAJOR_VERSION = Integer.parseInt(matcher.group(1));
    VAADIN_MINOR_VERSION = Integer.parseInt(matcher.group(2));
    VAADIN_REVISION = Integer.parseInt(matcher.group(3));
    if (matcher.groupCount() == 4) {
        VAADIN_BUILD = matcher.group(4);
    }
}