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:io.selendroid.client.waiter.WaitingConditions.java

License:Apache License

public static Callable<String> pageSourceToContain(final WebDriver driver, final String expectedText) {
    return new Callable<String>() {

        public String call() throws Exception {
            String source = driver.getPageSource();

            if (source.contains(expectedText)) {
                return source;
            }//from   ww w. j av a 2 s  . c  o  m

            return null;
        }

        @Override
        public String toString() {
            return "Page source to contain: " + expectedText;
        }
    };
}

From source file:io.tourniquet.selenium.SeleniumControlExample.java

License:Apache License

@Test
public void accessBaseUrl() throws Exception {

    WebDriver driver = SeleniumContext.currentDriver();

    assertNotNull(driver);//  w  w w  .java 2  s. c o m
    assertEquals("HOME", driver.getPageSource());
}

From source file:io.tourniquet.selenium.SeleniumControlExample.java

License:Apache License

@Test
public void getPage() throws Exception {

    WebDriver driver = SeleniumContext.currentDriver();

    driver.get(SeleniumContext.resolve("page1"));
    assertEquals("PAGE1", driver.getPageSource());

}

From source file:ohtu.Tester2.java

public static void main(String[] args) {
    WebDriver driver = new HtmlUnitDriver();
    driver.get("http://localhost:8090");
    WebElement element = driver.findElement(By.linkText("register new user"));
    element.click();//from w  ww. java  2s  . c om

    element = driver.findElement(By.name("username"));
    element.sendKeys("asdfasdf");
    element = driver.findElement(By.name("password"));
    element.sendKeys("asdf1234");
    element = driver.findElement(By.name("passwordConfirmation"));
    element.sendKeys("asdf1234");
    element = driver.findElement(By.name("add"));
    element.submit();

    System.out.println(driver.getPageSource().contains("Welcome to Ohtu App!"));
}

From source file:org.alfresco.selenium.FetchUtil.java

License:Open Source License

/**
 * Saves the current page as seen by the WebDriver
 * @param driver {@link WebDriver}/*from ww  w.  j  a v a2  s .c o m*/
 * @param filename name of the HTML file output
 * @throws PageCaptureException if error
 * @throws IOException
 */
public static void save(final WebDriver driver, final String filename) throws IOException {
    String sourceHtml = driver.getPageSource();
    String currentUrl = driver.getCurrentUrl();

    //download all assets: js,img and stylesheet.
    List<String> files = extractFiles(sourceHtml);
    List<String> urls = parseURL(files, getHost(driver), currentUrl);
    getFiles(urls, driver);
    String html = parseHtml(sourceHtml, files);
    File file = new File(OUTPUT_DIR + filename);
    file.delete();
    FileUtils.writeStringToFile(file, html);
}

From source file:org.apache.archiva.web.test.tools.WebdriverUtility.java

License:Apache License

public static Path takeScreenShot(String fileName, WebDriver driver) {
    Path result = null;//from   w w w.ja  v  a  2s. c  o m
    try {
        Path snapDir = Paths.get("target", "errorshtmlsnap");
        Path screenShotDir = Paths.get("target", "screenshots");
        if (!Files.exists(snapDir)) {
            Files.createDirectories(snapDir);
        }
        Path htmlFile = snapDir.resolve(fileName + ".html");
        Path screenShotFile = screenShotDir.resolve(fileName);
        String pageSource = null;
        String encoding = "ISO-8859-1";
        try {
            pageSource = ((JavascriptExecutor) driver)
                    .executeScript("return document.documentElement.outerHTML;").toString();
        } catch (Exception e) {
            log.info("Could not create html source by javascript");
            pageSource = driver.getPageSource();
        }
        if (pageSource.contains("encoding=\"")) {
            encoding = pageSource.replaceFirst(".*encoding=\"([^\"]+)\".*", "$1");
        }
        FileUtils.writeStringToFile(htmlFile.toFile(), pageSource, encoding);
        try {
            Path scrs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).toPath();
            Files.copy(scrs, screenShotFile);
        } catch (Exception e) {
            log.info("Could not create screenshot: " + e.getMessage());
        }

    } catch (IOException e) {
        log.info("Creating screenshot failed " + e.getMessage());
    }
    return result;
}

From source file:org.apache.nutch.protocol.htmlunit.HtmlUnitWebDriver.java

License:Apache License

public static String getHTMLContent(WebDriver driver, Configuration conf) {
    try {//from  w  ww  .  ja v a 2s .  c o m
        if (conf.getBoolean("take.screenshot", false))
            takeScreenshot(driver, conf);

        String innerHtml = "";
        if (enableJavascript) {
            WebElement body = driver.findElement(By.tagName("body"));
            innerHtml = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].innerHTML;",
                    body);
        } else
            innerHtml = driver.getPageSource().replaceAll("&amp;", "&");
        return innerHtml;
    } catch (Exception e) {
        TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles();
        cleanUpDriver(driver);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nutch.protocol.htmlunit.HtmlUnitWebDriver.java

License:Apache License

/**
 * Function for obtaining the HTML BODY using the selected
 * <a href='https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.html'>selenium webdriver</a>
 * There are a number of configuration properties within
 * <code>nutch-site.xml</code> which determine whether to
 * take screenshots of the rendered pages and persist them
 * as timestamped .png's into HDFS.//from ww w .j a  va  2 s.  co m
 * @param url the URL to fetch and render
 * @param conf the {@link org.apache.hadoop.conf.Configuration}
 * @return the rendered inner HTML page
 */
public static String getHtmlPage(String url, Configuration conf) {
    WebDriver driver = getDriverForPage(url, conf);

    try {
        if (conf.getBoolean("take.screenshot", false))
            takeScreenshot(driver, conf);

        String innerHtml = "";
        if (enableJavascript) {
            WebElement body = driver.findElement(By.tagName("body"));
            innerHtml = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].innerHTML;",
                    body);
        } else
            innerHtml = driver.getPageSource().replaceAll("&amp;", "&");
        return innerHtml;

    } catch (Exception e) {
        TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles();
        throw new RuntimeException(e);
    } finally {
        cleanUpDriver(driver);
    }
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

License:Apache License

/**
 * Most page can be fetched and parsed efficiently by Htmlunit, 
 * But some sites (such as ) using some special javascript tech that can't be processed by Htmlunit correctly,
 * We use Selenium WebDriver even lower process speed.
 * @param url// w  ww . j ava2s.c o  m
 * @throws Exception
 */
private void readPlainContentByWebDriver(URL url) throws Exception {

    String urlStr = url.toString();
    Http.LOG.debug("WebDriver fetching: " + url);
    String html = null;
    boolean ok = true;

    WebDriver driver = null;
    try {
        driver = new FirefoxDriver();
        driver.get(url.toString());

        int i = 0;
        while (i++ < MAX_AJAX_WAIT_SECONDS) {
            html = driver.getPageSource().trim();
            ok = isParseDataFetchLoaded(urlStr, html);
            if (ok) {
                break;
            }
            //Trigger scroll event to get ajax content                
            ((JavascriptExecutor) driver).executeScript("scroll(0," + (i * 500) + ");");
            Http.LOG.info("Sleep " + i + " seconds to wait WebDriver execution...");
            Thread.sleep(1000);
        }
    } finally {
        //Ensure driver quit
        if (driver != null) {
            driver.quit();
        }
    }

    if (ok) {
        Http.LOG.debug("Success parse page by WebDriver  for: {}", url);
        this.code = 200;
        content = html.getBytes();
    } else {
        Http.LOG.warn("Failure WebDriver parse page for: {}", url);
        Http.LOG.warn(
                "WebDriver Fetch Failure URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
    }
}

From source file:org.bigtester.ate.model.page.page.BasePageObject.java

License:Apache License

/**
 * @return the pageHtmlSource//  w w  w .j a  v a2s . c o m
 * We don't use member to store page source,
 * This function will make sure that the pageSource is always reflecting the current status of the page source.
 */
public String getPageHtmlSource() {
    //TODO to make sure that the events on page all finished before get source.
    ThinkTime newTT = new ThinkTime(10);
    newTT.setTimer();
    WebDriver webD = getMyWd().getWebDriver();
    if (null == webD) {
        throw GlobalUtils.createNotInitializedException("web driver");
    } else {
        String retVal = webD.getPageSource();
        if (null == retVal || !StringUtils.hasText(retVal)) {
            throw GlobalUtils.createInternalError("Web Driver internal error.!");
        }
        return retVal;
    }

}