Get Current URL
To get the the current URL of web page programmatically using Selenium in Java, initialize a web driver and call getCurrentUrl() method on the web driver object.
WebDriver.getCurrentUrl() method returns a string representing the current URL that the browser is looking at.
The following is a simple code snippet to initialize a web driver and get the URL of the current web page.
</>
Copy
WebDriver driver = new ChromeDriver();
//some code
String currentUrl = driver.getCurrentUrl();
Example
In the following program, we write Java code to initialize a web driver, visit google.com, search for the query 'tutorialkart', and get the current URL of that web page.
Java Program
</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyAppTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com/ncr");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("tutorialkart");
searchBox.sendKeys(Keys.RETURN);
String currentUrl = driver.getCurrentUrl();
System.out.println(currentUrl);
driver.quit();
}
}
Screenshots
1. Initialize web driver and navigate to google.com.
</>
Copy
WebDriver driver = new ChromeDriver();
driver.get("https://google.com/ncr");
