Selenium Click Link: Different Ways to Automate Link Clicks
Clicking links is one of the most basic things a user can do on a website. If you're writing test scripts, it’s also one of the most common actions you’ll need to automate.
With Selenium WebDriver, you can interact with any hyperlink on the page, no matter if it's visible, hidden, dynamic, or opens in a new tab. All you need is the right locator and a clear understanding of how the browser responds.
In this article, we’ll walk you through:
- How to click a hyperlink using Selenium
- Working examples in both Python and Java
- Ways to locate links using link text, XPath, CSS, and more
- Handling links that open in a new tab or window
- The difference between click and submit
- Common issues and best practices for automating hyperlink clicks
Let’s dive in and learn how to automate link clicks with confidence using Selenium click link techniques.
Steps to click a hyperlink in Selenium WebDriver
Clicking a link with Selenium WebDriver is a simple process. You launch the browser, find the link, and simulate a user click using the built-in method. This lets your automation follow links just like a real person would.
Step 1: Launch the browser and open the target page. Choose any website you want to test. Selenium will start the session and load the URL.
Step 2: Locate the hyperlink using a Selenium locator strategy. You can use link text, partial link text, XPath, CSS selector, or an attribute like href.
Step 3: Use the click method to simulate interaction. Selenium will trigger the same behavior as a user click.
Step 4: Verify that the link worked. You can check the page title, URL, or the presence of specific content to confirm the navigation was successful.
Example of how to click a hyperlink in Selenium WebDriver
Here are two quick examples showing how to use selenium click link in both Java and Python. These samples demonstrate how to locate a link by text, click it, and confirm the page has changed.
Python example using link text
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://katalon.com")
# Click the link using full link text
link = driver.find_element(By.LINK_TEXT, "Platform")
link.click()
# Print the current page title
print(driver.title)
driver.quit()
Java example using partial link text
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClickLinkExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://katalon.com");
// Click the link using partial link text
driver.findElement(By.partialLinkText("Plat")).click();
// Print the current page title
System.out.println(driver.getTitle());
driver.quit();
}
}
These examples show how the selenium click link method works using both full and partial link text. You can use this approach for most hyperlinks that are clearly labeled on the page.
Different ways to locate a hyperlink in Selenium
Before you can use the selenium click link method, you need to identify the hyperlink accurately. Selenium provides several ways to do this, and each has its own advantages depending on the structure of the page.
- By link text: This method matches the exact text between the anchor tags. It works best when the link label is static and clearly defined.
- By partial link text: This option matches a part of the text. It is useful when the full text is long, dynamic, or contains variable content.
- By XPath: Use this when you want to locate the link based on its attributes or hierarchy. You can match href values, parent-child structure, or any attribute combination.
- By CSS selector: This method targets the link using a CSS pattern. It works well when the anchor tag has unique classes or href values.
- By attributes: You can use custom attributes like title, data-id, or even aria-label. These provide flexibility for locating links that are not easily identified by visible text.
When using Selenium click link techniques, choose the most unique and stable locator available. This keeps your test scripts reliable across page changes and layout updates.
Handling links that open in new tabs or windows
Some hyperlinks open content in a new tab or window instead of the same view. In those cases, your script needs to shift focus and return later with a clean flow that mirrors real user behavior.
Step 1: Capture the current window’s identifier using getWindowHandle().
Step 2: After clicking the link, collect all open window handles using getWindowHandles(). This gives you access to the new tab or window.
Step 3: Switch context to the new window using switchTo().window(handle).
Step 4: Perform any checks or actions within the new window. Then close it or switch back to the original using its handle.
Here is a Python example illustrating the flow:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://katalon.com")
original = driver.current_window_handle
driver.find_element_by_link_text("Open in new tab").click()
for handle in driver.window_handles:
if handle != original:
driver.switch_to.window(handle)
print("New tab title:", driver.title)
driver.close()
break
driver.switch_to.window(original)
print("Back to original title:", driver.title)
driver.quit()
This pattern ensures your script stays in sync with the browser context. It mirrors user behavior of opening a link, verifying content, and returning to the starting point, creating tests that are both reliable and understandable.
Click vs Submit: Key Difference
In Selenium automation, both .click() and .submit() simulate user actions, but they serve distinct purposes. Understanding when to use each one makes your test cases cleaner and more predictable.
- The .click() method is ideal for simulating mouse clicks. It works well on hyperlinks, buttons, and interactive elements that respond to user interaction. If you want to test a navigation flow by clicking a link, this is the method you need. It fits perfectly in any selenium click link scenario.
- The .submit() method triggers form submissions. It should be used when the action is tied to an HTML form element. For example, you might locate an input field and call .submit() on its parent form to initiate the process.
Here’s a helpful tip: links are not form elements, so calling .submit() on a hyperlink won't trigger navigation. Stick with .click() when your goal is to follow a link or press a button outside a form.
With this distinction clear, your Selenium click link commands will behave exactly as expected and help you avoid confusion while scripting tests.
Common issues when clicking hyperlinks in Selenium
Even simple actions like simulating a link click with Selenium can encounter unexpected challenges. Understanding common problems and effective debugging techniques will help your automation run smoothly every time.
- ElementNotInteractableException occurs when a link is hidden or covered by an overlay. You can use an explicit wait or scroll the element into view before clicking to avoid this.
- StaleElementReferenceException happens when the page structure changes before the click happens. Re-locate the element right before clicking to ensure you interact with a fresh reference.
- Intercepted clicks happen when popups or ads block the link. Waiting for those elements to disappear or using a more precise locator helps ensure the click succeeds.
- Duplicate link text can lead Selenium to click the wrong element. Use unique locators, index selection, or flags like CSS class or a specific attribute to distinguish the correct link.
By combining proper waits, accurate locators, and visual context, your selenium click link commands can stay resilient in the face of dynamic page changes. This keeps your automation reliable and easy to maintain.
Best practices for clicking hyperlinks in Selenium
This checklist helps you build stable and reliable automation scripts. Following these guidelines improves maintainability and test clarity.
- Prefer By.linkText or By.partialLinkText when the link label is clear. It makes locator definitions readable and direct.
- Validate navigation after a click. Always check the page title or URL to confirm that your selenium click link command performed as expected.
- Use explicit waits before clicking when elements appear dynamically. Waiting for visibility prevents timing mismatches and improves script reliability.
- Avoid brittle XPath for hyperlinks unless you need to target a specific part of the DOM. Simple locators are easier to maintain.
- Centralize locators in a separate object or module. It simplifies updates when UI changes, and helps teams reuse locator definitions across multiple tests.
These practices help your Selenium scripts stay clean, predictable, and easy to update. They support consistent usage of selenium click link commands and make link interactions more reliable overall.
How Katalon can help automate better?
Selenium itself is a browser automation library, so you still need a framework for test management, execution, reporting, and integration. With Katalon Studio, you get the power of Selenium in a full-featured automation platform.
This means you don’t have to hand-code everything from scratch (project structure, test runners, reporting, environment setup). Katalon lets you write Selenium-powered tests faster with built-in record/playback, test objects management, and a keyword-driven interface while still allowing custom code in Groovy/Java where needed.
- Keyword-driven simplicity: Use built-in keywords to interact with UI elements quickly and reliably. Scripts stay clean even as your test suite grows.
- Fast-start learning resource: The free Using Built-in Keywords in Katalon course teaches you how to build tests using test objects and reusable keywords.
- Official reference for click behavior: The Katalon WebUI.click() docs explain how Katalon automatically retries click actions when overlays are present.
- Object Repository Integration: All UI elements are stored in one place. You can reuse them across multiple test cases without writing locators from scratch.
- Cross-browser and mobile support: You can run your click tests across Chrome, Firefox, Safari, Edge, Android, and iOS using the same test logic.
- Low-code test authoring: In Manual Mode, you build tests using drag-and-drop. Then switch to Script Mode for more control when needed.
- Expandable via custom keywords: Create your own keywords when your use case needs a tailored action or extra logic.
- Robust debugging and maintainability: Every test run includes screenshots, logs, and execution history to speed up your troubleshooting.
- CI/CD & reporting integration: Plug Katalon into Jenkins, GitHub Actions, or any CI pipeline. Reports are automatically generated after each run.
