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.gargoylesoftware.htmlunit.javascript.host.Location2Test.java

License:Apache License

/**
 * @throws Exception if the test fails/*from   ww w. jav a2s  .  c om*/
 */
@Test
public void changeLocationToNonHtml() throws Exception {
    final String html = "<html><head>\n" + "  <script>\n" + "      document.location.href = 'foo.txt';\n"
            + "  </script>\n" + "</head>\n" + "<body></body></html>";

    getMockWebConnection().setResponse(new URL(URL_FIRST, "foo.txt"), "bla bla", "text/plain");
    final WebDriver driver = loadPage2(html, URL_FIRST);
    assertTrue(driver.getPageSource().contains("bla bla"));
}

From source file:com.gargoylesoftware.htmlunit.libraries.PrototypeTestBase.java

License:Apache License

/**
 * Runs the specified test./*from  w w  w  .  ja va  2s.co  m*/
 * @param filename the test file to run
 * @throws Exception if the test fails
 */
protected void test(final String filename) throws Exception {
    final WebDriver driver = getWebDriver();
    if (!(driver instanceof HtmlUnitDriver)) {
        try {
            driver.manage().window().setSize(new Dimension(1272, 768));
        } catch (final WebDriverException e) {
            // ChromeDriver version 0.5 (Mar 26, 2013) does not support the setSize command
            LOG.warn(e.getMessage(), e);
        }
    }
    driver.get(getBaseUrl() + filename);

    // wait
    final long runTime = 60 * DEFAULT_WAIT_TIME;
    final long endTime = System.currentTimeMillis() + runTime;

    while (!testFinished(driver)) {
        Thread.sleep(100);

        if (System.currentTimeMillis() > endTime) {
            fail("Test '" + filename + "' runs too long (longer than " + runTime / 1000 + "s)");
        }
    }

    String expected = getExpectations(getBrowserVersion(), filename);
    WebElement testlog = driver.findElement(By.id("testlog"));
    String actual = testlog.getText();

    try {
        testlog = driver.findElement(By.id("testlog_2"));
        actual = actual + "\n" + testlog.getText();
    } catch (final NoSuchElementException e) {
        // ignore
    }

    // ignore Info lines
    expected = expected.replaceAll("Info:.*", "Info: -- skipped for comparison --");
    actual = actual.replaceAll("Info:.*", "Info: -- skipped for comparison --");

    // normalize line break
    expected = expected.replaceAll("\r\n", "\n");
    actual = actual.replaceAll("\r\n", "\n");

    // dump the result page if not ok
    if (System.getProperty(PROPERTY_GENERATE_TESTPAGES) != null && !expected.equals(actual)) {
        final File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        final File f = new File(tmpDir, "prototype" + getVersion() + "_result_" + filename);
        FileUtils.writeStringToFile(f, driver.getPageSource(), UTF_8);
        LOG.info("Test result for " + filename + " written to: " + f.getAbsolutePath());
    }

    assertEquals(expected, actual);
}

From source file:com.github.licanhua.test.framework.AbstractWebDriverProvider.java

License:Apache License

public void takesScreenshot(WebDriverContext webDriverContext) {
    if (!webDriverContext.isAutoSnapshot()) {
        logger.debug("autoSnapshot is disabled. skip the snapshot");
        return;//from w  w w .ja va2 s.  co m
    }
    String path = TEST_OUT + driverTimeStamp + "/" + testName + "/" + snapCount++;
    logger.info("Snapshot to : " + path);
    WebDriver webDriver = webDriverContext.getWebDriver();
    File screenshotAs = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);

    try {
        FileUtils.copyFile(screenshotAs, new File(path + "-screenshot.png"));
        FileUtils.writeStringToFile(new File(path + "-source.html"), webDriver.getPageSource(),
                Charset.defaultCharset(), false);
    } catch (IOException e) {
        logger.error("Fail to save snapshot", e);
    }
}

From source file:com.github.swt_release_fetcher.SwtWebsite.java

License:Apache License

/**
 * Determines if the website has changed since our last visit. Uses a file
 * called ''pageSource'' to persist the site
 *
 * @param driver/* w  ww . j  ava 2 s  .co  m*/
 * @param websiteUrl URL to SWT's project site
 * @return true if the site has changed, false if not. Also returns true on
 * the first run
 * @throws IOException If the file ''pageSource'' coudln't be read or
 * written
 */
public boolean hasChanged(WebDriver driver, String websiteUrl) throws IOException {

    driver.get(websiteUrl);
    String pageSoruce = driver.getPageSource();
    String persistedPageSource = "";
    File f = new File("pageSource");
    // create a new file to persist page source
    if (!f.exists()) {
        try {
            f.createNewFile();
        } catch (IOException ieo) {
            throw new IOException("Unable to create file " + f.getAbsolutePath(), ieo);
        }
        // if it was already there, this is not the first run of swt-release-fetcher
        // read in the file content
    } else {
        try {
            persistedPageSource = FileUtils.readFileToString(f, "utf-8");
        } catch (IOException ieo) {
            throw new IOException("Unable to read file " + f.getAbsolutePath(), ieo);
        }
    }

    // check if the page has changed
    if (persistedPageSource.equals(pageSoruce)) {
        return false;
        // NOTE: If this is the first run of swt-release-fethcer the file 
        // will be empty and thus filled with content here
    } else {
        try {
            FileUtils.writeStringToFile(f, pageSoruce);
            return true;
        } catch (IOException ieo) {
            throw new IOException("Unable to write to file " + f.getAbsolutePath(), ieo);
        }

    }
}

From source file:com.google.appengine.tck.env.appspot.AppspotLoginHandler.java

License:Open Source License

public void login(WebDriver driver, LoginContext context) {
    try {/*from   w ww.j a  v a 2s .c  o  m*/
        WebElement email = driver.findElement(By.id("Email"));
        if (email.getAttribute("readonly") == null) {
            email.clear();
            email.sendKeys(context.getEmail());
        }

        WebElement password = driver.findElement(By.id("Passwd"));
        password.sendKeys(context.getPassword());

        driver.findElement(By.name("signIn")).click();
    } catch (NoSuchElementException e) {
        throw new IllegalStateException(
                String.format("URL[%s]\n\n%s", driver.getCurrentUrl(), driver.getPageSource()), e);
    }
}

From source file:com.ibm.sbt.automation.core.environment.TestEnvironment.java

License:Open Source License

/**
 * Dump the page source to the trace log
 *//*ww w. j a v  a 2s  . c o m*/
public void dumpPageSource(WebDriver webDriver) {
    String pageSource = webDriver.getPageSource();
    Trace.log("Page source: " + pageSource);
}

From source file:com.java.AppTestType_18_11_2015.java

public void VERIFYQAINAMP(WebDriver driver, String fieldText) throws FileNotFoundException {

    String field = fieldText;//from   w w  w. ja  va  2s.  c  om

    try {

        // driver.findElement(By.linkText("ALL EQUIPMENT")).click();
        /* driver.navigate().to("http://e1.dev.assetnation.com/all-equipment/equipmentone-listings");
        driver.findElement(By.linkText("2")).click();
                
        Thread.sleep(10000);
                
        List <WebElement> listings = driver.findElements(By.cssSelector("a[href*='/listing?listingid']"));
                
        Random r = new Random();
         int randomValue = r.nextInt(listings.size()); //Getting a random value that is between 0 and (list's size)-1
         listings.get(randomValue).click();
        Thread.sleep(10000);*/
        NAVIGATETOLISTINGDETAILSPAGE(driver);

        getvalue = driver.findElement(By.xpath("//*[@id='ONengine']/div[7]/span")).getText();

        System.out.println(getvalue);
        // SUMAN

        driver.findElement(By.xpath("//input[@type='button' and @value='Ask it Now']")).click();
        Thread.sleep(2000);
        driver.findElement(By.id("listingQuestion")).click();
        String question = "Where is the listing located?" + Time;
        driver.findElement(By.id("listingQuestion")).sendKeys(question);
        Thread.sleep(1000);
        driver.findElement(By.name("submitq")).click();
        Thread.sleep(4000);
        driver.findElement(By.xpath("(//input[@value='OK'])[2]")).click();
        Thread.sleep(4000);

        /* driver.findElement(By.id("uname")).click();
           Thread.sleep(10000);
           driver.findElement(By.linkText("Sign Out")).click();*/
        SIGNOUT(driver);

        driver.manage().deleteAllCookies();
        driver.navigate().refresh();

        driver.get(field);
        driver.manage().deleteAllCookies();
        driver.findElement(By.id("aurid")).sendKeys("mglaz@assetnation.com");

        driver.findElement(By.id("apwd")).sendKeys("Equipment1$");
        driver.findElement(By.xpath("//input[@value='Login']")).click();

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

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

        Thread.sleep(2000);

        System.out.println("Searching for lot id : " + getvalue);
        driver.findElement(By.name("search_string")).clear();
        driver.findElement(By.name("search_string")).sendKeys(getvalue);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        ;
        driver.findElement(By.xpath("//button")).click();

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

        driver.findElement(By.linkText("Lot Q/A")).click();

        if (driver.getPageSource().contains(question)) {
            //driver.navigate().refresh();
            resultDetails.setFlag(true);
        } else
            System.out.println("question not found in AMP");

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

        //       FileOutputStream fos = new FileOutputStream("C:/TestProject - DEV/Log File/logfile.txt");
        //        PrintStream ps = new PrintStream(fos);
        //        e.printStackTrace(ps);
    }
}

From source file:com.java.AppTestType_18_11_2015.java

public void BUYINGSALESINMYONE(WebDriver driver, String fieldText) {

    String field = fieldText;//  ww  w. j av  a2s.c  om

    AppKeyWords ampkey = AppKeyWords.valueOf(field.toUpperCase());

    switch (ampkey) {

    case MAXOFFER:

        try {

            MAXOFFERINDETAILSPAGE(driver);

            driver.findElement(By.xpath("//li[@id='e1lnk_myone']/a")).click();

            Thread.sleep(10000);

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

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

                resultDetails.setErrorMessage("listing is displayed in myone> buying");

                resultDetails.setFlag(true);
            }

        } catch (Exception e) {

            resultDetails.setFlag(false);

            break;
        }

    case EXACTOFFER:
        try {

            EXACTOFFERINDETAILSPAGE(driver);

            driver.findElement(By.xpath("//li[@id='e1lnk_myone']/a")).click();

            Thread.sleep(10000);

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

            String LISTINGIDINMYONE = driver
                    .findElement(By.xpath("//div[12]/div/div[5]/div/div/div[2]/div/div/div[2]")).getText();

            if (LISTINGIDINMYONE.equalsIgnoreCase(ListingsID)) {

                resultDetails.setErrorMessage("listing is displayed in myone> buying");

            }

        } catch (Exception e) {

            resultDetails.setFlag(false);
        }

        break;
    }

}

From source file:com.java.AppTestType_18_11_2015.java

public void BUYINGQA(WebDriver driver) {

    try {// w  ww  .  j a  v  a2 s  .c om

        QA(driver);
        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[2]/ul/li[2]/a")).click();
        Thread.sleep(10000);

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

            resultDetails.setFlag(true);
        }

    } catch (Exception e) {

        resultDetails.setFlag(false);
        resultDetails.setErrorMessage("Qusetion is not displayed in MyONE");
        e.printStackTrace();
    }
}

From source file:com.java.AppTestType_18_11_2015.java

public void WATCHINGINMYONE(WebDriver driver, String fieldText) {

    try {/* w ww.  ja v  a  2s. co  m*/
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        ADDTOWATCHLIST(driver, fieldText);
        System.out.println("Back to  WATCHINGINMYONE method");

        driver.findElement(By.xpath("(//a[contains(text(),'MyONE')])[2]")).click();

        driver.findElement(By.xpath("(//a[contains(text(),'Watching')])[2]")).click();

        if (driver.getPageSource().contains(ListingID)) {
            System.out.println("listing is found in myone pagesource");
            resultDetails.setFlag(true);
        }
    } catch (Exception e) {
        System.out.println("Listing added is not displayed in MYOne Watchlist");
        resultDetails.setFlag(false);

    }

}