Selenium get current url after loading a page

670    Asked by CarolynBuckland in QA Testing , Asked on Jun 7, 2021

I'm using Selenium Webdriver in Java. I want to get the current URL after clicking the "next" button to move from page 1 to page 2. Here's the code I have:

   WebDriver driver = new FirefoxDriver();
    String startURL = //a starting url;
    String currentURL = null;
    WebDriverWait wait = new WebDriverWait(driver, 10);
    foo(driver,startURL);
    /* go to next page */
    if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
        driver.findElement(By.xpath("//*[@id='someID']")).click();  
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='someID']")));
        currentURL = driver.getCurrentUrl();
        System.out.println(currentURL);
    }   

I have both the implicit and explicit wait calls to wait for the page to be fully loaded before I get the current URL. However, it's still printing out the URL for page 1 (it's expected to be the URL for page 2).

Answered by Colin Payne

Since the path for the next button is the same on every page, it is basically not going to work. It's working on the initial page as the code includes the method to let the browser wait for the element to be displayed but since it (the web-element) is already displayed, the implicit wait won’t get applied because it doesn't need to wait at all. Why don't you use the fact that the selenium gets the current url changed when the next button is clicked. Your code needs to be changed. In order to do that you can use the below shown Java code:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting URL;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
foo(driver,startURL);
/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    ExpectedCondition e = new ExpectedCondition() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };
    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
}

Your Answer

Interviews

Parent Categories