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

The following examples show how to use org.openqa.selenium.WebDriver#getCurrentUrl() . 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: HTMLDocumentTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = "?%C3%A8=%C3%A8",
        IE = "?\u00E8=\u00E8")
public void encoding7() throws Exception {
    final String html = "<html>\n"
        + "<head>\n"
        + "<meta charset='UTF-8'>\n"
        + "</head><body>\n"
        + "  <a id='myId' href='test?\u00E8=\u00E8'>test</a>\n"
        + "</body></html>";
    getMockWebConnection().setDefaultResponse("Error: not found", 404, "Not Found", MimeType.TEXT_HTML);

    final WebDriver driver = loadPage2(html, URL_FIRST, MimeType.TEXT_HTML, UTF_8);
    driver.findElement(By.id("myId")).click();
    String actualQuery = driver.getCurrentUrl();
    actualQuery = actualQuery.substring(actualQuery.indexOf('?'));
    assertTrue(actualQuery.endsWith(getExpectedAlerts()[0]));
}
 
Example 2
Source File: TransitionErrorException.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Build the message for this transition error exception.
 * 
 * @param context container context in which the error was detected
 * @param errorMessage error message
 * @return transition error exception message
 */
private static String buildMessage(ComponentContainer context, String errorMessage) {
    StringBuilder builder = new StringBuilder("Transition error detected: ").append(errorMessage);
    builder.append("\nContainer: ").append(Enhanceable.getContainerClass(context).getName());
    WebDriver driver = context.getWrappedDriver();
    if (driver != null) {
        String pageUrl = driver.getCurrentUrl();
        if (pageUrl != null) {
            builder.append("\nPage URL: ").append(pageUrl);
        }
        String pageTitle = driver.getTitle();
        if (pageTitle != null) {
            builder.append("\nPage title: ").append(pageTitle);
        }
    }
    return builder.toString();
}
 
Example 3
Source File: CustomConditions.java    From opentest with MIT License 6 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits for the current page URL
 * to match the provided regular expression.
 */
public static ExpectedCondition<Boolean> urlToMatch(final Pattern regexPattern) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            String url = driver.getCurrentUrl();
            Boolean matches = regexPattern.matcher(url).matches();
            return matches;
        }

        @Override
        public String toString() {
            return "current page URL to match: " + regexPattern.toString();
        }
    };
}
 
Example 4
Source File: SelectPage.java    From oxAuth with MIT License 6 votes vote down vote up
public LoginPage clickOnLoginAsAnotherUser() {
    final WebDriver driver = driver();

    output("Removed session_id");
    driver.manage().deleteCookieNamed("session_id"); // emulate browser

    final String previousUrl = driver.getCurrentUrl();
    output("Clicked Login as another user button");
    getLoginAsAnotherUserButton().click();
    waitForPageSwitch(previousUrl);

    navigate(driver.getCurrentUrl());
    if (BaseTest.ENABLE_REDIRECT_TO_LOGIN_PAGE) {
        new WebDriverWait(driver, PageConfig.WAIT_OPERATION_TIMEOUT)
                .until((WebDriver d) -> !d.getCurrentUrl().contains("/authorize"));
    }
    return new LoginPage(config);
}
 
Example 5
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation for the URL of the current page to be a specific url.
 *
 * @param url the url that the page should be on
 * @return <code>true</code> when the URL is what it should be
 */
public static ExpectedCondition<Boolean> urlToBe(final String url) {
  return new ExpectedCondition<Boolean>() {
    private String currentUrl = "";

    @Override
    public Boolean apply(WebDriver driver) {
      currentUrl = driver.getCurrentUrl();
      return currentUrl != null && currentUrl.equals(url);
    }

    @Override
    public String toString() {
      return String.format("url to be \"%s\". Current url: \"%s\"", url, currentUrl);
    }
  };
}
 
Example 6
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * An expectation for the URL of the current page to contain specific text.
 *
 * @param fraction the fraction of the url that the page should be on
 * @return <code>true</code> when the URL contains the text
 */
public static ExpectedCondition<Boolean> urlContains(final String fraction) {
  return new ExpectedCondition<Boolean>() {
    private String currentUrl = "";

    @Override
    public Boolean apply(WebDriver driver) {
      currentUrl = driver.getCurrentUrl();
      return currentUrl != null && currentUrl.contains(fraction);
    }

    @Override
    public String toString() {
      return String.format("url to contain \"%s\". Current url: \"%s\"", fraction, currentUrl);
    }
  };
}
 
Example 7
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Expectation for the URL to match a specific regular expression
 *
 * @param regex the regular expression that the URL should match
 * @return <code>true</code> if the URL matches the specified regular expression
 */
public static ExpectedCondition<Boolean> urlMatches(final String regex) {
  return new ExpectedCondition<Boolean>() {
    private String currentUrl;
    private Pattern pattern;
    private Matcher matcher;

    @Override
    public Boolean apply(WebDriver driver) {
      currentUrl = driver.getCurrentUrl();
      pattern = Pattern.compile(regex);
      matcher = pattern.matcher(currentUrl);
      return matcher.find();
    }

    @Override
    public String toString() {
      return String
        .format("url to match the regex \"%s\". Current url: \"%s\"", regex, currentUrl);
    }
  };
}
 
Example 8
Source File: AuthorizationCodeTest.java    From ebay-oauth-java-client with Apache License 2.0 5 votes vote down vote up
private String getAuthorizationResponseUrl() throws InterruptedException {
    // Optional, if not specified, WebDriver will search your path for chromedriver.
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");

    WebDriver driver = new ChromeDriver();
    OAuth2Api auth2Api = new OAuth2Api();
    String authorizeUrl = auth2Api.generateUserAuthorizationUrl(EXECUTION_ENV, SCOPE_LIST, Optional.of("current-page"));

    driver.get(authorizeUrl);
    Thread.sleep(5000);

    WebElement userId = (new WebDriverWait(driver, 10))
            .until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("input[type='text']"))));
    WebElement password = driver.findElement(By.cssSelector("input[type='password']"));

    userId.sendKeys(CRED_USERNAME);
    password.sendKeys(CRED_PASSWORD);
    driver.findElement(By.name("sgnBt")).submit();

    Thread.sleep(5000);

    String url = null;
    if (driver.getCurrentUrl().contains("code=")) {
        printDetailedLog("Code Obtained");
        url = driver.getCurrentUrl();
    } else {
        WebElement agreeBtn = (new WebDriverWait(driver, 10))
                .until(ExpectedConditions.visibilityOf(driver.findElement(By.id("submit"))));

        agreeBtn.submit();
        Thread.sleep(5000);
        url = driver.getCurrentUrl();
    }
    driver.quit();
    return url;
}
 
Example 9
Source File: HttpWebConnection3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * An expectation for checking that the current url contains a case-sensitive substring.
 *
 * @param url the fragment of url expected
 * @return true when the url matches, false otherwise
 */
public static ExpectedCondition<Boolean> currentUrlContains(final String url) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(final WebDriver driver) {
            final String currentUrl = driver.getCurrentUrl();
            return currentUrl != null && currentUrl.contains(url);
        }
    };
}
 
Example 10
Source File: WebDriverConfig.java    From jmeter-plugins-webdriver with Apache License 2.0 5 votes vote down vote up
protected boolean hasThreadBrowser() {
    if (webdrivers.containsKey(currentThreadName())) {
        WebDriver browser = webdrivers.get(currentThreadName());
        try {
            browser.getCurrentUrl();
            return true;
        } catch (Exception ex) {
            LOGGER.warn("Old browser object is inaccessible, will create new", ex);
            webdrivers.remove(currentThreadName());
        }
    }
    return false;
}
 
Example 11
Source File: Page.java    From SeleniumBestPracticesBook with Apache License 2.0 5 votes vote down vote up
public void verify(WebDriver selenium) throws URISyntaxException {
  URI uri = new URI(selenium.getCurrentUrl());
  if (!uri.getPath().equals(getPagePath())) {
    throw new RuntimeException(
        "Unexpected page. Expected " + getPagePath() + " but current url is " + selenium
            .getCurrentUrl());
  }
}
 
Example 12
Source File: EbayIdTokenValidatorTest.java    From ebay-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public String getIdTokenResponseUrl(String nonce) throws InterruptedException {
    // Optional, if not specified, WebDriver will search your path for chromedriver.
    System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");

    WebDriver driver = new ChromeDriver();
    OAuth2Api authApi = new OAuth2Api();
    String idTokenUrl = authApi.generateIdTokenUrl(EXECUTION_ENV, Optional.of("current-page"), nonce);

    driver.get(idTokenUrl);
    Thread.sleep(5000);

    WebElement userId = (new WebDriverWait(driver, 10))
            .until(ExpectedConditions.visibilityOf(driver.findElement(By.cssSelector("input[type='text']:not([name='userid_otp']):not([name='otp'])"))));

    WebElement password = driver.findElement(By.cssSelector("input[type='password']"));
    userId.sendKeys(CRED_USERNAME);
    password.sendKeys(CRED_PASSWORD);
    WebElement sgnBt = null;
    try {
        sgnBt = driver.findElement(By.name("sgnBt"));
    } catch (NoSuchElementException e) {
        // ignore exception
    }
    if (sgnBt == null) {
        sgnBt = driver.findElement(By.id("sgnBt"));
    }

    sgnBt.submit();
    Thread.sleep(5000);

    String url = null;
    if (driver.getCurrentUrl().contains("id_token=")) {
        printDetailedLog("Id Token Obtained");
        url = driver.getCurrentUrl();
    } else {
        WebElement agreeBtn = (new WebDriverWait(driver, 10))
                .until(ExpectedConditions.visibilityOf(driver.findElement(By.id("submit"))));

        agreeBtn.submit();
        Thread.sleep(5000);
        url = driver.getCurrentUrl();
    }
    driver.quit();
    printDetailedLog(url);
    return url;
}
 
Example 13
Source File: BrowserPageNavigation.java    From webtau with Apache License 2.0 4 votes vote down vote up
public static void refresh(WebDriver driver) {
    driver.navigate().refresh();
    String fullUrl = driver.getCurrentUrl();
    onOpenedPage(fullUrl, fullUrl, fullUrl);
}
 
Example 14
Source File: GitCrawler.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void scanCurrentPage(WebDriver driver, int page) {
    String current = driver.getCurrentUrl();

    /*
        Note: there were layout changes in the past on Github page.
        Practically every year...
     */
    //String xpath = "//h3[@class='repo-list-name']/a";
    //String xpath = "//div[@class='container']//ul//h3//a";
    //String xpath = "//ul[contains(@class,'repo-list')]//h3//a";
    String xpath = "//ul[contains(@class,'repo-list')]//div[contains(@class,'f4 text-normal')]//a";

    List<WebElement> projects = driver.findElements(By.xpath(xpath));
    List<String> names = projects.stream().map(p -> p.getText()).collect(Collectors.toList());

    System.out.println("Going to analyze "+names.size()+" projects in this page at: "+current);

    while (!names.isEmpty()) {

        String name = names.remove(0);

        By byName = By.xpath(xpath + "[text()='" + name + "']");
        WebElement a = getElement(driver, byName, page);
        a.click();
        Boolean loaded = waitForPageToLoad(driver);

        if (loaded) {

            /*
                Checking if either Maven or Gradle

                Note: not a robust check:
                - build files might not be in root folder
                - no check if there was any error in the loaded page
             */
            List<WebElement> maven = driver.findElements(By.xpath("//td[contains(@class,'content')]//a[@title='pom.xml']"));
            if (!maven.isEmpty()) {
                System.out.println("" + name + " uses Maven");
            } else {
                List<WebElement> gradle =  driver.findElements(By.xpath("//td[contains(@class,'content')]//a[@title='build.gradle']"));
                if (!gradle.isEmpty()) {
                    System.out.println("" + name + " uses Gradle");
                } else {
                    System.out.println("" + name + " undefined build system");
                }
            }
        }

        /*
                do not overflow GitHub of requests. 10 per minutes should be more than enough.
                Recall: "If you would like to crawl GitHub contact us at [email protected]."
                from  https://github.com/robots.txt
        */
        sleep(6000);

        driver.get(current);
        waitForPageToLoad(driver);

        sleep(6000);
    }
}
 
Example 15
Source File: GitCrawler.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void scanCurrentPage(WebDriver driver, int page) {
    String current = driver.getCurrentUrl();

    /*
        Note: there were layout changes in the past on Github page.
        Practically every year...
     */
    //String xpath = "//h3[@class='repo-list-name']/a";
    //String xpath = "//div[@class='container']//ul//h3//a";
    //String xpath = "//ul[contains(@class,'repo-list')]//h3//a";
    String xpath = "//ul[contains(@class,'repo-list')]//div[contains(@class,'f4 text-normal')]//a";

    List<WebElement> projects = driver.findElements(By.xpath(xpath));
    List<String> names = projects.stream().map(p -> p.getText()).collect(Collectors.toList());

    System.out.println("Going to analyze "+names.size()+" projects in this page at: "+current);

    while (!names.isEmpty()) {

        String name = names.remove(0);

        By byName = By.xpath(xpath + "[text()='" + name + "']");
        WebElement a = getElement(driver, byName, page);
        a.click();
        Boolean loaded = waitForPageToLoad(driver);

        if (loaded) {

            /*
                Checking if either Maven or Gradle

                Note: not a robust check:
                - build files might not be in root folder
                - no check if there was any error in the loaded page
             */
            List<WebElement> maven = driver.findElements(By.xpath("//td[contains(@class,'content')]//a[@title='pom.xml']"));
            if (!maven.isEmpty()) {
                System.out.println("" + name + " uses Maven");
            } else {
                List<WebElement> gradle =  driver.findElements(By.xpath("//td[contains(@class,'content')]//a[@title='build.gradle']"));
                if (!gradle.isEmpty()) {
                    System.out.println("" + name + " uses Gradle");
                } else {
                    System.out.println("" + name + " undefined build system");
                }
            }
        }

        /*
                do not overflow GitHub of requests. 10 per minutes should be more than enough.
                Recall: "If you would like to crawl GitHub contact us at [email protected]."
                from  https://github.com/robots.txt
        */
        sleep(6000);

        driver.get(current);
        waitForPageToLoad(driver);

        sleep(6000);
    }
}