In this blog, I'll show you how to navigate to any URL in the browser using Selenium.
Example:
Let's say we want to land on the official Selenium website: https://www.selenium.dev/
Here's how we do it:
Take the URL of the website you want to navigate to. In this case, we'll use the Selenium website as an example.
In Selenium, there’s a method called
get()
, which comes from the WebDriver interface. All browser driver classes implement their version of this method to load a URL in the browser.Simply type
driver.get("
https://www.selenium.dev/
");
. Ensure the URL is a string enclosed in quotes.
When you run this, the Chrome browser will open and navigate to selenium.dev
.
Getting the Page Title
Next, let's fetch the title of the page:
Hover your cursor over the tab in the browser, and you'll see the title displayed (e.g., "Selenium").
Selenium provides a method
driver.getTitle()
to get the current page title programmatically.Here’s the code:
String title = driver.getTitle(); System.out.println("Page title: " + title);
This will print the page title in the console.
Validating the Current URL
To ensure you’ve landed on the correct page and not been redirected, use the driver.getCurrentUrl()
method:
String currentUrl = driver.getCurrentUrl();
System.out.println("Current URL: " + currentUrl);
Closing the Browser
After the test, you should always close the browser to free up system resources. Selenium provides two methods for this:
driver.close()
driver.quit()
Key Difference Between close()
and quit()
close()
: Closes only the current window or tab where the browser is focused.quit()
: Closes all browser windows opened by Selenium during the session.
Example Scenario:
If your script opens multiple tabs or windows, use
quit()
to close them all.If you’re working with a single tab,
close()
is sufficient.
Sample Code:
driver.get("https://www.selenium.dev/");
System.out.println("Page Title: " + driver.getTitle());
System.out.println("Current URL: " + driver.getCurrentUrl());
driver.close();
- Always log outputs to the console using
System.out.println
to validate results during testing.
That’s it. We explored how to navigate to a URL in Selenium, fetch the page title, validate the current URL, and close the browser properly. These fundamental operations are essential for automating browser interactions effectively.
Check out the complete Selenium Series for more such articles!
Let’s get connected!