Java Code Examples for org.openqa.selenium.WebDriver#getPageSource()

The following examples show how to use org.openqa.selenium.WebDriver#getPageSource() . 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: 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 2
Source File: PageSourceUtils.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Produce page source from the specified driver.
 * 
 * @param optDriver optional web driver object
 * @param reason impetus for capture request; may be 'null'
 * @param logger SLF4J logger object; may be 'null'
 * @return page source; if capture fails, an empty string is returned
 */
public static String getArtifact(
                final Optional<WebDriver> optDriver, final Throwable reason, final Logger logger) {
    
    if (canGetArtifact(optDriver, logger)) {
        try {
            WebDriver driver = optDriver.get();
            StringBuilder sourceBuilder = new StringBuilder(driver.getPageSource());
            insertBaseElement(sourceBuilder, driver);
            insertBreakpointInfo(sourceBuilder, reason);
            insertOriginalUrl(sourceBuilder, driver);
            return sourceBuilder.toString();
        } catch (WebDriverException e) {
            if (logger != null) {
                logger.warn("The driver is capable of producing page source, but failed.", e);
            }
        }
    }
    return "";
}
 
Example 3
Source File: HtmlUnknownElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void asXml() throws Exception {
    final String html
        = "<html><body><title>foo</title>\n"
        + "<foo></foo>\n"
        + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);

    final String xml = driver.getPageSource();
    assertTrue("Node not expanded in: " + xml, xml.contains("</foo>"));
}
 
Example 4
Source File: SeleniumCrawlerClient.java    From PicCrawler with Apache License 2.0 5 votes vote down vote up
public void downloadPic(String url) {

        WebDriver driver = new ChromeDriver();

        driver.get(url);
        String html = driver.getPageSource();
        List<String> urls = parseHtmlToImages(html,picParser);
        crawlerClient.downloadPics(urls);
    }
 
Example 5
Source File: WaitStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Waits a period of time for the presence of some text on the page.
 *
 * @param wait          The maximum amount of time to wait for
 * @param alias         This text appears if the text is actually an alias key
 * @param text          The text to find on the page, or the alias to the text
 * @param ignoreTimeout If this text is present in the step, the step will silently fail if the
 *                      requested page text could not be found
 * @throws InterruptedException Thread.sleep was interrupted
 */
@Then("^I wait \"(\\d+)\" seconds for the page to contain the text( alias)? \"(.*?)\"(,? ignoring timeouts?)?")
public void verifyPageContent(final Integer wait, final String alias, final String text, final String ignoreTimeout) throws InterruptedException {
	final String fixedText = autoAliasUtils.getValue(text, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());

	final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();

	final long start = System.currentTimeMillis();

	String pageText = null;

	do {
		/*
			getText() can fail here, we we use the innerText attribute instead.
			https://github.com/AutoGeneral/IridiumApplicationTesting/issues/109
		 */
		 pageText = webDriver.findElement(By.tagName("body")).getAttribute("innerText");

		if (pageText != null && pageText.contains(fixedText)) {
			return;
		}

		Thread.sleep(Constants.TIME_SLICE);

	}
	while (System.currentTimeMillis() - start < wait * Constants.MILLISECONDS_PER_SECOND);

	if (StringUtils.isBlank(ignoreTimeout)) {
		throw new ValidationException("Could not find the text \"" + fixedText + "\" on the page with the text:\n"
			+ pageText + "\n"
			+ "and page source:\n"
			+ webDriver.getPageSource());
	}
}
 
Example 6
Source File: GetXmlPageObject.java    From PatatiumWebUi with Apache License 2.0 5 votes vote down vote up
public  static void getXmlPageObject()
{
	WebDriver driver=new FirefoxDriver();
	driver.get("http://192.168.0.29:9020/hospital/load");
	String tString=driver.getPageSource();
	System.out.println(tString);
}
 
Example 7
Source File: GetXmlPageObject.java    From PatatiumAppUi with GNU General Public License v2.0 5 votes vote down vote up
public  static void getXmlPageObject()
{
	WebDriver driver=new FirefoxDriver();
	driver.get("http://192.168.0.29:9020/hospital/load");
	String tString=driver.getPageSource();
	System.out.println(tString);
}
 
Example 8
Source File: WebDriverAftBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * <p>
 * Logs in using the KRAD Login Page, if the JVM arg remote.autologin is set, auto login as admin will not be done.
 * </p>
 *
 * @param driver to login with
 * @param userName to login with
 * @param failable to fail on if there is a login problem
 * @throws InterruptedException
 */
public void login(WebDriver driver, String userName, JiraAwareFailable failable) throws InterruptedException {
    if ("true".equalsIgnoreCase(System.getProperty(WebDriverUtils.REMOTE_AUTOLOGIN_PROPERTY, "true"))) {
        driver.findElement(By.name("login_user")).clear();
        driver.findElement(By.name("login_user")).sendKeys(userName);
        driver.findElement(By.id("Rice-LoginButton")).click();
        Thread.sleep(1000);
        String contents = driver.getPageSource();
        AutomatedFunctionalTestUtils.failOnInvalidUserName(userName, contents, failable);
        AutomatedFunctionalTestUtils.checkForIncidentReport(driver.getPageSource(), "Login", "Login failure",
                failable);
    }
}
 
Example 9
Source File: WebDriverITBase.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * <p>
 * Logs in using the KRAD Login Page, if the JVM arg remote.autologin is set, auto login as admin will not be done.
 * </p>
 *
 * @param driver to login with
 * @param userName to login with
 * @param failable to fail on if there is a login problem
 * @throws InterruptedException
 */
public void login(WebDriver driver, String userName, JiraAwareFailable failable) throws InterruptedException {
    if ("true".equalsIgnoreCase(System.getProperty(WebDriverUtils.REMOTE_AUTOLOGIN_PROPERTY, "true"))) {
        driver.findElement(By.name("login_user")).clear();
        driver.findElement(By.name("login_user")).sendKeys(userName);
        driver.findElement(By.id("Rice-LoginButton")).click();
        Thread.sleep(1000);
        String contents = driver.getPageSource();
        AutomatedFunctionalTestUtils.failOnInvalidUserName(userName, contents, failable);
        AutomatedFunctionalTestUtils.checkForIncidentReport(driver.getPageSource(), "Login",
                "Login failure", failable);
    }
}
 
Example 10
Source File: SeleniumPhantomjsPageLoader.java    From xxl-crawler with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Document load(PageRequest pageRequest) {
    if (!UrlUtil.isUrl(pageRequest.getUrl())) {
        return null;
    }

    // driver init
    DesiredCapabilities dcaps = new DesiredCapabilities();
    dcaps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, !pageRequest.isValidateTLSCertificates());
    dcaps.setCapability(CapabilityType.TAKES_SCREENSHOT, false);
    dcaps.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true);
    dcaps.setJavascriptEnabled(true);
    if (driverPath!=null && driverPath.trim().length()>0) {
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, driverPath);
    }

    if (pageRequest.getProxy() != null) {
        dcaps.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
        dcaps.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
        System.setProperty("http.nonProxyHosts", "localhost");
        dcaps.setCapability(CapabilityType.PROXY, pageRequest.getProxy());
    }

    /*dcaps.setBrowserName(BrowserType.CHROME);
    dcaps.setVersion("70");
    dcaps.setPlatform(Platform.WIN10);*/

    WebDriver webDriver = new PhantomJSDriver(dcaps);

    try {
        // driver run
        webDriver.get(pageRequest.getUrl());

        if (pageRequest.getCookieMap() != null && !pageRequest.getCookieMap().isEmpty()) {
            for (Map.Entry<String, String> item: pageRequest.getCookieMap().entrySet()) {
                webDriver.manage().addCookie(new Cookie(item.getKey(), item.getValue()));
            }
        }

        webDriver.manage().timeouts().implicitlyWait(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);
        webDriver.manage().timeouts().pageLoadTimeout(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);
        webDriver.manage().timeouts().setScriptTimeout(pageRequest.getTimeoutMillis(), TimeUnit.MILLISECONDS);

        String pageSource = webDriver.getPageSource();
        if (pageSource != null) {
            Document html = Jsoup.parse(pageSource);
            return html;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (webDriver != null) {
            webDriver.quit();
        }
    }
    return null;
}
 
Example 11
Source File: GetHtmlSource.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
  return driver.getPageSource();
}
 
Example 12
Source File: ClosureTestStatement.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public void evaluate() throws Throwable {
  URL testUrl = filePathToUrlFn.apply(testPath);
  LOG.info("Running: " + testUrl);

  Stopwatch stopwatch = Stopwatch.createStarted();

  WebDriver driver = driverSupplier.get();

  if (!isOnTravis()) {
    // Attempt to make the window as big as possible.
    try {
      driver.manage().window().maximize();
    } catch (RuntimeException ignored) {
      // We tried.
    }
  }

  JavascriptExecutor executor = (JavascriptExecutor) driver;
  // Avoid Safari JS leak between tests.
  executor.executeScript("if (window && window.top) window.top.G_testRunner = null");

  try {
    driver.get(testUrl.toString());
  } catch (WebDriverException e) {
    fail("Test failed to load: " + e.getMessage());
  }

  while (!getBoolean(executor, Query.IS_FINISHED)) {
    long elapsedTime = stopwatch.elapsed(TimeUnit.SECONDS);
    if (timeoutSeconds > 0 && elapsedTime > timeoutSeconds) {
      throw new JavaScriptAssertionError("Tests timed out after " + elapsedTime + " s. \nCaptured Errors: " +
                                         ((JavascriptExecutor) driver).executeScript("return window.errors;")
                                         + "\nPageSource: " + driver.getPageSource() + "\nScreenshot: " +
                                         ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64));
    }
    TimeUnit.MILLISECONDS.sleep(100);
  }

  if (!getBoolean(executor, Query.IS_SUCCESS)) {
    String report = getString(executor, Query.GET_REPORT);
    throw new JavaScriptAssertionError(report);
  }
}
 
Example 13
Source File: HTMLLauncher.java    From selenium with Apache License 2.0 4 votes vote down vote up
/**
 * Launches a single HTML Selenium test suite.
 *
 * @param browser - the browserString ("*firefox", "*iexplore" or an executable path)
 * @param startURL - the start URL for the browser
 * @param suiteURL - the relative URL to the HTML suite
 * @param outputFile - The file to which we'll output the HTML results
 * @param timeoutInSeconds - the amount of time (in seconds) to wait for the browser to finish
 * @return PASS or FAIL
 * @throws IOException if we can't write the output file
 */
public String runHTMLSuite(
  String browser,
  String startURL,
  String suiteURL,
  File outputFile,
  long timeoutInSeconds,
  String userExtensions) throws IOException {
  File parent = outputFile.getParentFile();
  if (parent != null && !parent.exists()) {
    parent.mkdirs();
  }
  if (outputFile.exists() && !outputFile.canWrite()) {
    throw new IOException("Can't write to outputFile: " + outputFile.getAbsolutePath());
  }
  long timeoutInMs = 1000L * timeoutInSeconds;
  if (timeoutInMs < 0) {
    log.warning("Looks like the timeout overflowed, so resetting it to the maximum.");
    timeoutInMs = Long.MAX_VALUE;
  }

  WebDriver driver = null;
  try {
    driver = createDriver(browser);
    URL suiteUrl = determineSuiteUrl(startURL, suiteURL);

    driver.get(suiteUrl.toString());
    Selenium selenium = new WebDriverBackedSelenium(driver, startURL);
    selenium.setTimeout(String.valueOf(timeoutInMs));
    if (userExtensions != null) {
      selenium.setExtensionJs(userExtensions);
    }
    List<WebElement> allTables = driver.findElements(By.id("suiteTable"));
    if (allTables.isEmpty()) {
      throw new RuntimeException("Unable to find suite table: " + driver.getPageSource());
    }
    Results results = new CoreTestSuite(suiteUrl.toString()).run(driver, selenium, new URL(startURL));

    HTMLTestResults htmlResults = results.toSuiteResult();
    try (Writer writer = Files.newBufferedWriter(outputFile.toPath())) {
      htmlResults.write(writer);
    }

    return results.isSuccessful() ? "PASSED" : "FAILED";
  } finally {
    if (server != null) {
      try {
        server.stop();
      } catch (Exception e) {
        // Nothing sane to do. Log the error and carry on
        log.log(Level.INFO, "Exception shutting down server. You may ignore this.", e);
      }
    }

    if (driver != null) {
      driver.quit();
    }
  }
}
 
Example 14
Source File: SeleniumCrawlerClient.java    From PicCrawler with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param url
 * @param scrollDownNum 模拟鼠标滚动到屏幕底部到次数
 */
public void downloadPic(String url,int scrollDownNum) {

    WebDriver driver = new ChromeDriver();

    driver.get(url);
    String html = driver.getPageSource();
    List<String> urls = parseHtmlToImages(html,picParser);

    crawlerClient.downloadPics(urls);

    if (scrollDownNum>1) {

        for (int i=0;i<scrollDownNum-1;i++) {

            Utils.scrollDown(driver);

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            html = driver.getPageSource();

            urls = parseHtmlToImages(html,picParser);

            crawlerClient.downloadPics(urls);
        }
    }
}