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:qhcloud.selenium.TestSuite.createTenantStatic.java

public static void main(String[] arg) throws BiffException, IOException {

    String ERROR_CODE_FAILURE = "{\"allErrorCodes\":[{\"errorCode\":18},{\"errorCode\":8}]}";
    String baseURL = "http://www.google.com";
    File file = new File("C:\\Users\\akshaya\\Desktop\\selenium\\data_file.xls");
    Workbook workbook = Workbook.getWorkbook(file);
    Sheet sheet = workbook.getSheet(0);/*from w  w  w.jav  a 2 s .c om*/

    String link = sheet.getCell(2, 1).getContents();
    String action = sheet.getCell(3, 1).getContents();
    String name = sheet.getCell(4, 1).getContents();
    String reference = sheet.getCell(5, 1).getContents();
    String contactNumber = sheet.getCell(6, 1).getContents();
    String raName = sheet.getCell(7, 1).getContents();
    String raEmail = sheet.getCell(8, 1).getContents();
    String raMobileNumber = sheet.getCell(9, 1).getContents();
    String cloudLicenseKey = sheet.getCell(10, 1).getContents();
    String duration = sheet.getCell(11, 1).getContents();
    String totalProducts = sheet.getCell(12, 1).getContents();
    String productKey = sheet.getCell(13, 1).getContents();
    String type = sheet.getCell(14, 1).getContents();
    String version = sheet.getCell(15, 1).getContents();
    String expiryDate = sheet.getCell(16, 1).getContents();
    String count = sheet.getCell(17, 1).getContents();
    String language = sheet.getCell(18, 1).getContents();
    String copyType = sheet.getCell(19, 1).getContents();

    String cretaeTenentAPI = link + ("={\"action\" : \"") + action + ("\",\"name\": \"") + name
            + ("\",\"reference\" : \"") + reference + ("\",\"contactNumber\" : \"") + contactNumber
            + ("\",\"raName\": \"") + raName + ("\",\"raEmail\" : \"") + raEmail
            + ("\",\"raMobileNumber\" : \"") + raMobileNumber + ("\",\"cloudLicenseKey\" : \"")
            + cloudLicenseKey + ("\",\"duration\" : ") + duration + (",\"totalProducts\" : ") + totalProducts
            + (",\"productsInfo\" : [{\"productKey\" : \"") + productKey + ("\",\"type\" : ") + type
            + (",\"version\" : \"") + version + ("\",\"expiryDate\" : ") + expiryDate + (",\"count\" : ")
            + count + ("}],\"language\": ") + language + (",\"copyType\":") + copyType + "}";
    System.out.println(cretaeTenentAPI);

    /*   String actualapi = sheet.getCell(0, 2).getContents();
       System.out.println(actualapi);
    */

    WebDriver driver = new FirefoxDriver();

    driver.get(baseURL);

    driver.get(cretaeTenentAPI);
    String pagesource = driver.getPageSource();
    String returnCode = driver.findElement(By.tagName("pre")).getText().trim();

    /* if(returnCode.equalsIgnoreCase(ERROR_CODE_FAILURE))*/
    System.out.println("ERROR CODE = " + returnCode);

    //System.out.println(cretaeTenentAPI);

}

From source file:seleniumsample.SeleniumSample.java

public static void InvokeSelenium(String pstrSearchkeyword) {
    try {/*from   w ww  . j  a va2s .c  om*/
        WebDriver driver = new HtmlUnitDriver();
        driver.get("http://www.google.com");
        WebElement lobjelement = driver.findElement(By.name("q"));
        lobjelement.sendKeys(pstrSearchkeyword);
        lobjelement.submit();
        char[] lobjBuffer = driver.getPageSource().toCharArray();
        //lobjfilewriter.write(lobjBuffer);
        //String lstrpath=file.getAbsolutePath();
        //System.out.println(mstrSearchkeyword+" File successfully created at!! "+lstrpath);
        WriteTheContentToTextFile(lobjBuffer, pstrSearchkeyword);
        driver.quit();

    } catch (Exception lobjException) {
        Logger.getLogger(SeleniumSample.class.getName()).log(Level.SEVERE, null, lobjException);

    }
}

From source file:sf.wicklet.test.support.SeleniumTestUtil.java

License:Apache License

public static void takeSnapshot(final boolean debug, final WebDriver driver, final File htmlfile,
        final File pngfile) throws IOException {
    if (debug) {//from  w ww  . java2s  .  co  m
        final String text = driver.getPageSource();
        System.out.println(text);
        if (htmlfile != null) {
            FileUtil.writeFile(htmlfile, false, text);
        }
        if (pngfile != null) {
            takeScreenshot((TakesScreenshot) driver, pngfile);
        }
    }
}

From source file:stepparsing.StepParsing.java

public static String getRegisteredAccount(WebDriver driver, String login) {
    String AccEmail = login;//from   www.  ja va 2s  . com

    driver.get("https://www.amazon.com");

    try {
        Thread.sleep(1000 * 5);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }

    WebElement regDiv = driver.findElement(By.id(("nav-flyout-ya-signin")));
    WebElement regAElement = regDiv.findElement(By.tagName("a"));
    String regLink = regAElement.getAttribute("href");
    if (!regLink.contains("https://www.amazon.com")) {
        regLink = "https://www.amazon.com" + regLink;
    }
    driver.get(regLink);
    try {
        Thread.sleep(1000 * 5);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }

    WebElement newRegAElement = driver.findElement(By.id("createAccountSubmit"));
    String newRegLink = newRegAElement.getAttribute("href");
    if (!newRegLink.contains("https://www.amazon.com")) {
        regLink = "https://www.amazon.com" + regLink;
    }
    driver.get(newRegLink);
    try {
        Thread.sleep(1000 * 10);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }

    WebElement nameInput = driver.findElement(By.id("ap_customer_name"));
    nameInput.sendKeys("Petrov");
    WebElement emailInput = driver.findElement(By.id("ap_email"));
    emailInput.sendKeys(AccEmail);
    WebElement passInput = driver.findElement(By.id("ap_password"));
    passInput.sendKeys("123456789");
    WebElement passCheckInput = driver.findElement(By.id("ap_password_check"));
    passCheckInput.sendKeys("123456789");
    WebElement submitInput = driver.findElement(By.id("continue"));
    try {
        Thread.sleep(1000 * 60);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
    submitInput.click();

    try {
        Thread.sleep(1000 * 5);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }

    String curURL = driver.getCurrentUrl();
    driver.get(curURL);
    try {
        Thread.sleep(1000 * 5);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
    if (driver.getPageSource().contains("Petrov")) {
        WebDriverFactory.dismissDriver(driver);
        return AccEmail;
    } else {
        AccEmail = "";
        System.out.println("Registrstion didn't complite!");
    }

    WebDriverFactory.dismissDriver(driver);

    return AccEmail;
}

From source file:test.org.ocpsoft.rewrite.cdi.concurrency.ConcurrencyTest.java

License:Apache License

@Test
public void testManyConcurrentDeferredRequests() throws Exception {

    final int NUMBER_OF_THREADS = 20;
    final int REQUESTS_PER_THREAD = 5;

    final AtomicInteger successCounter = new AtomicInteger(0);

    ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    for (int thread = 0; thread < NUMBER_OF_THREADS; thread++) {
        executor.submit(new Runnable() {
            @Override/*from  w  ww  . ja va 2 s  .c o  m*/
            public void run() {
                for (int i = 0; i < REQUESTS_PER_THREAD; i++) {
                    String uuid = UUID.randomUUID().toString();

                    WebDriver driver = new HtmlUnitDriver();
                    driver.get(baseUrl + "test/" + uuid + "/");

                    if (driver.getPageSource().contains("The parameter is [" + uuid + "]")) {
                        successCounter.addAndGet(1);
                    } else {
                        System.out.println("foo!");
                    }
                }
            }
        });
    }

    executor.shutdown();
    executor.awaitTermination(20, TimeUnit.SECONDS);
    executor.shutdownNow();

    assertEquals(NUMBER_OF_THREADS * REQUESTS_PER_THREAD, successCounter.get());

}

From source file:testselenium.TestSel.java

public static String getProveOfLogin(String email, String password) throws InterruptedException { // 86 - 96   ?      ?    
    String logginedPage = "";

    System.setProperty("webdriver.gecko.driver", "C:\\selenium\\geckodriver.exe"); //   ? 

    WebDriver driver = new FirefoxDriver(); //   profile ? default
    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); //?  ?
    driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS); //?  ?

    driver.get("https://www.amazon.com/");

    WebElement authLinkBtn = driver.findElement(By.id("nav-flyout-ya-signin"));
    WebElement authLinkElement = authLinkBtn.findElement(By.tagName("a"));
    String loginLink = authLinkElement.getAttribute("href");

    driver.get(loginLink); //   ? ,    

    WebElement inputEmailField = driver.findElement(By.id("ap_email"));
    inputEmailField.sendKeys(email);/* w  w  w. j  a v  a  2 s  .  co  m*/

    WebElement inputPassField = driver.findElement(By.id("ap_password"));
    inputPassField.sendKeys(password);

    WebElement authBtn = driver.findElement(By.id("signInSubmit"));
    authBtn.click(); // ??   ""

    Thread.sleep(1000 * 5); //    ?  20 ? ?    ?

    //   ?  ?   ? ??   click

    String logginedPageLink = driver.getCurrentUrl();
    driver.get(logginedPageLink);

    Thread.sleep(1000 * 10); //    ?  20 ? 

    logginedPage = driver.getPageSource(); //  logginedPage  ? .  ?  ?  ? ?? ? (   Hello? name!

    return logginedPage;

}

From source file:wsattacker.sso.openid.attacker.evaluation.attack.KeyConfusionAttack.java

License:Open Source License

@Attack(number = 1)
private AttackResult performSecondVariantOfKeyConfusionAttack() {
    OpenIdServerConfiguration.getAttackerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAttackerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAnalyzerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAnalyzerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAttackerInstance().setPerformAttack(true);

    String victimIdp = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration().getBaseUrl();

    AttackParameter opEndpointParameter = keeper.getParameter("openid.op_endpoint");
    opEndpointParameter.setAttackValueUsedForSignatureComputation(true);
    opEndpointParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    opEndpointParameter.setAttackMethod(HttpMethod.GET);
    opEndpointParameter.setAttackValue(victimIdp);

    String victimIdentity = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration()
            .getIdentity();/*  w w w  .ja  v a  2 s .co m*/

    AttackParameter claimedIdParameter = keeper.getParameter("openid.claimed_id");
    claimedIdParameter.setAttackValueUsedForSignatureComputation(true);
    claimedIdParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    claimedIdParameter.setAttackMethod(HttpMethod.GET);
    claimedIdParameter.setAttackValue(victimIdentity);

    AttackParameter identityParameter = keeper.getParameter("openid.identity");
    identityParameter.setAttackValueUsedForSignatureComputation(true);
    identityParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    identityParameter.setAttackMethod(HttpMethod.GET);
    identityParameter.setAttackValue(victimIdentity);

    // include modified parameter in signature
    AttackParameter sigParameter = keeper.getParameter("openid.sig");
    sigParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    sigParameter.setAttackMethod(HttpMethod.GET);

    // copy log entries before login
    List<RequestLogEntry> logEntriesBeforeLogin = new ArrayList<>(RequestLogger.getInstance().getEntryList());

    LoginResult loginResultAttacker = serviceProvider.login(ServiceProvider.User.ATTACKER);

    WebDriver driver = SeleniumBrowser.getWebDriver();
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    String url = serviceProvider.getUrl();
    jse.executeScript("var win = window.open('" + url + "');");

    List<String> windowhandles = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(windowhandles.get(1));

    LoginResult loginResultVictim = serviceProvider.login(ServiceProvider.User.VICTIM);

    driver.switchTo().window(windowhandles.get(0));

    List<WebElement> links = driver.findElements(By.tagName("a"));
    links.get(1).click();

    /* determines the log entries of the current login procedure:
       logEntries = logEntriesAfterLogin - logEntriesBeforeLogin
       (subtraction of sets) */
    List<RequestLogEntry> logEntriesAfterLogin = RequestLogger.getInstance().getEntryList();
    List<RequestLogEntry> logEntries = (List<RequestLogEntry>) CollectionUtils.subtract(logEntriesAfterLogin,
            logEntriesBeforeLogin);

    // invert order of log - should be chronological
    Collections.reverse(logEntries);

    loginResultAttacker.setScreenshot(SeleniumBrowser.takeScreenshot());
    loginResultAttacker.setLogEntries(logEntries);

    boolean success = serviceProvider.determineAuthenticatedUser(driver.getPageSource(),
            driver.getCurrentUrl()) == User.VICTIM;
    Result result = success ? Result.SUCCESS : Result.FAILURE;
    Interpretation interpretation = success ? Interpretation.CRITICAL : Interpretation.PREVENTED;

    if (loginResultAttacker.hasDirectVerification()) {
        result = Result.NOT_PERFORMABLE;
        interpretation = Interpretation.NEUTRAL;
    }

    assert isSignatureValid(loginResultAttacker) : "Signature is not valid!";

    // close second window
    driver.switchTo().window(windowhandles.get(1)).close();
    driver.switchTo().window(windowhandles.get(0));

    return new AttackResult("Second Variant of Key Confusion", loginResultAttacker, result, interpretation);
}

From source file:wsattacker.sso.openid.attacker.evaluation.strategies.InjectJavaScriptLoginStrategy.java

License:Open Source License

@Override
public LoginResult login(User user, ServiceProvider serviceProvider) {
    // before loginAndDetermineAuthenticatedUser remove all cookies
    SeleniumBrowser.deleteAllCookies();//from  www. j  av a2  s  .  c o m

    // copy log entries before login
    List<RequestLogEntry> logEntriesBeforeLogin = new ArrayList<>(RequestLogger.getInstance().getEntryList());

    // open url
    WebDriver driver = SeleniumBrowser.getWebDriver();
    driver.get(serviceProvider.getUrl());

    /* Search the page for the OpenID input field. According to the
       standard it should be called "openid_identifier" but some other
       frequent names are also tried. */
    WebElement element = null;
    String[] possibleNames = { "openid_identifier", "openid", "openID", "openid_url", "openid:url", "user",
            "openid-url", "openid-identifier", "oid_identifier", "ctl00$Column1Area$OpenIDControl1$openid_url",
            "user_input", "openIdUrl" };

    for (String possibleName : possibleNames) {
        try {
            element = driver.findElement(By.name(possibleName));
            System.out.println("Find OpenID field with name: " + possibleName);
            break;
        } catch (NoSuchElementException exception) {
            //System.out.println("Cannot find: " + possibleName);
        }
    }

    // save old XRDS lcoation
    String oldIdentity = OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration().getIdentity();

    /* If an input field is found, it is filled with the OpenID identifier.
       Selenium cannot set text of hidden input field, consequently,
       JavaScript is injected which performs this task. */
    if (element != null) {
        JavascriptExecutor jse = (JavascriptExecutor) driver;

        // set text of text field
        switch (user) {
        case VICTIM:
            jse.executeScript("arguments[0].value='" + serviceProvider.getVictimOpenId() + "'", element);
            break;
        case ATTACKER:
            jse.executeScript("arguments[0].value='" + serviceProvider.getAttackerOpenId() + "'", element);
            break;
        case ATTACKER_RANDOM:
            String attackerOpenId = serviceProvider.getAttackerOpenId();

            if (attackerOpenId.endsWith("/")) {
                attackerOpenId = attackerOpenId.substring(0, attackerOpenId.length() - 1);
            }

            String randomAttackerIdentity = attackerOpenId + RandomStringUtils.random(10, true, true);
            OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration()
                    .setIdentity(randomAttackerIdentity);
            jse.executeScript("arguments[0].value='" + randomAttackerIdentity + "'", element);
            break;
        }

        // special case: owncloud
        if (driver.getCurrentUrl().contains("owncloud")) {
            // set arbitrary password
            WebElement passwordElement = driver.findElement(By.id("password"));
            passwordElement.clear();
            passwordElement.sendKeys("xyz");

            WebElement submitElement = driver.findElement(By.id("submit"));

            jse.executeScript("var element = arguments[0]; element.removeAttribute('id');", submitElement);
        }

        // submit form
        if (element.isDisplayed()) {
            // element.submit(); // does not work as expected
            element.sendKeys(Keys.RETURN);
        } else {
            jse.executeScript("var element = arguments[0];" + "while(element.tagName != 'FORM') {"
                    + "element = element.parentNode;" + "console.log(element);" + "}" + "element.submit();",
                    element);
        }
    }

    // click on accept in modal alert window (if present)
    try {
        driver.switchTo().alert().accept();
    } catch (NoAlertPresentException ex) {
        // do nothing
    }

    // wait 10 seconds: hopefully, all redirects are performed then
    try {
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        Logger.getLogger(ServiceProvider.class.getName()).log(Level.SEVERE, null, ex);
    }

    /* determines the log entries of the current login procedure:
       logEntries = logEntriesAfterLogin - logEntriesBeforeLogin
       (subtraction of sets) */
    List<RequestLogEntry> logEntriesAfterLogin = RequestLogger.getInstance().getEntryList();
    List<RequestLogEntry> logEntries = (List<RequestLogEntry>) CollectionUtils.subtract(logEntriesAfterLogin,
            logEntriesBeforeLogin);

    // invert order of log - should be chronological
    Collections.reverse(logEntries);

    File screenshot = SeleniumBrowser.takeScreenshot();
    String pageSource = driver.getPageSource();

    // restore old XRDS location
    OpenIdServerConfiguration.getAttackerInstance().getHtmlConfiguration().setIdentity(oldIdentity);

    return new LoginResult(pageSource, logEntries, screenshot, driver.getCurrentUrl());
}

From source file:xxx.web.comments.roomfordebate.NYTimesCommentsScraper.java

License:Apache License

/**
 * Downloads the page and rolls out the entire discussion using {@link FirefoxDriver}.
 *
 * @param articleUrl url, e.g. {@code http://www.nytimes.com/roomfordebate/2015/02/04/regulate-internet-providers/the-internet-is-back-to-solid-regulatory-ground}
 * @return generated HTML code of the entire page
 * @throws InterruptedException// ww  w.jav a2 s.c  o  m
 */
public String readHTML(String articleUrl) throws InterruptedException {
    // load the url
    WebDriver driver = new FirefoxDriver();
    driver.get(articleUrl);

    // roll-out the entire discussion
    List<WebElement> commentsExpandElements;
    do {
        commentsExpandElements = driver.findElements(By.cssSelector("div.comments-expand"));

        // click on each of them
        for (WebElement commentsExpandElement : commentsExpandElements) {
            // only if visible & enabled
            if (commentsExpandElement.isDisplayed() && commentsExpandElement.isEnabled()) {
                commentsExpandElement.click();

                // give it some time to load new comments
                Thread.sleep(3000);
            }
        }
    }
    // until there is one remaining that doesn't do anything...
    while (commentsExpandElements.size() > 1);

    // get the html
    String result = driver.getPageSource();

    // close firefox
    driver.close();

    return result;
}

From source file:zz.pseas.ghost.login.taobao.LogInTaobao.java

License:Apache License

@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {

    String tbuserNmae = "TBname";
    String tbpassWord = "TBpasssword";

    String url = "https://login.taobao.com/member/login.jhtml";
    WebDriver ie = BrowserFactory.getIE();
    ie.get(url);//  w  w w .  j  av a 2 s  . c o m

    Thread.sleep(5000L);

    Set<Cookie> cookies = ie.manage().getCookies();
    CookieStore store = DownloadUtil.convertToCookieStore(cookies);

    GhostClient client = new GhostClient("utf-8", store);

    String html = ie.getPageSource();
    String pbk = Jsoup.parse(html).select("input#J_PBK").attr("value");
    String pwd1 = RsaUtil.enCode(pbk, "10001", tbuserNmae);

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("TPL_username", tbuserNmae);
    map.put("TPL_password", tbpassWord);
    map.put("fc", "default");
    map.put("from", "tb");
    map.put("gvfdcname", "10");
    map.put("keyLogin", "false");
    map.put("loginASR", "1");
    map.put("loginASRSuc", "1");
    map.put("loginType", "3");
    map.put("loginsite", "0");
    map.put("naviVer", "firefox|47");

    String ncoToken = Jsoup.parse(html).select("input#J_NcoToken").attr("value");
    map.put("ncoToken", ncoToken);

    map.put("newMini", "false");
    map.put("newMini2", "false");
    map.put("newlogin", "0");
    map.put("osVer", "windows|6.1");
    map.put("oslanguage", "zh-cn");
    map.put("qrLogin", "true");
    map.put("slideCodeShow", "false");
    map.put("sr", "1920*1080");

    String ua = Jsoup.parse(html).select("input#UA_InputId").attr("value");
    //map.put("ua", ua);

    String umToken = Jsoup.parse(html).select("input[name=um_token]").attr("value");
    map.put("um_token", umToken); // TODO get um_token

    String ans = client.post("https://login.taobao.com/member/login.jhtml", map);
    System.out.println(ans);
}