<div class="selenium-notes">
<h1>Links in Selenium</h1>
<p>Links are one of the most common web elements found in web applications. They are used to navigate users from one page to another page, open external websites, download files, navigate to different sections of the same page, open documents, launch new tabs or windows, and perform other navigation-related actions.</p>
<p>In Selenium WebDriver, links can be located and interacted with using different locator strategies such as <code>linkText()</code>, <code>partialLinkText()</code>, <code>id</code>, <code>name</code>, <code>className</code>, <code>tagName</code>, CSS Selector, and XPath. Selenium can also verify whether links are displayed, enabled, clickable, correctly pointing to the expected URL, and navigating to the expected destination.</p>
<p>These detailed notes explain links in Selenium from basic HTML concepts to advanced automation scenarios such as dynamic links, external links, links opening in new tabs, download links, multiple links, links inside tables, iframes, Shadow DOM, dynamic content, waits, Page Object Model, TestNG, reusable utilities, practical projects, and interview questions.</p>
<p>For structured Selenium automation learning, you can explore the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a> and use the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a> option.</p>
<hr>
<h2>1. What is a Link?</h2>
<p>A link, also called a hyperlink, is an HTML element that allows users to navigate from one location to another. In HTML, links are generally created using the <code><a></code> anchor element.</p>
<p>Example:</p>
<pre><code><a href="https://example.com">Visit Example</a></code></pre>
<p>In this example, <code><a></code> is the anchor element, <code>href</code> contains the destination URL, and <code>Visit Example</code> is the visible link text.</p>
<hr>
<h2>2. Why Links Are Important in Selenium Automation</h2>
<p>Links are important because navigation is a major part of web application workflows. Selenium testers frequently need to click links and verify that the correct page opens.</p>
<ul>
<li>Navigation testing</li>
<li>Page redirection testing</li>
<li>Menu testing</li>
<li>Footer link testing</li>
<li>External website validation</li>
<li>Download link testing</li>
<li>New tab or window testing</li>
<li>Broken link testing</li>
<li>Dynamic link testing</li>
<li>End-to-end workflow testing</li>
</ul>
<hr>
<h2>3. Basic HTML Link Structure</h2>
<pre><code><a href="https://www.example.com">Example Website</a></code></pre>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>HTML Part</th><th>Purpose</th></tr>
<tr><td><code><a></code></td><td>Defines a hyperlink</td></tr>
<tr><td><code>href</code></td><td>Specifies the destination</td></tr>
<tr><td>Example Website</td><td>Visible link text</td></tr>
</table>
<hr>
<h2>4. Understanding the href Attribute</h2>
<p>The <code>href</code> attribute specifies where the link should navigate.</p>
<pre><code><a href="https://example.com">Open Website</a></code></pre>
<p>Selenium can retrieve the <code>href</code> attribute using <code>getAttribute()</code>.</p>
<pre><code>String url = driver.findElement(
By.linkText("Open Website")
).getAttribute("href");
System.out.println(url);</code></pre>
<hr>
<h2>5. Setting Up Selenium</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LinkExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.quit();
}
}</code></pre>
<hr>
<h2>6. Locating Links Using Link Text</h2>
<p>Selenium provides <code>linkText()</code> for locating an anchor element using its complete visible text.</p>
<pre><code>driver.findElement(
By.linkText("About Us")
).click();</code></pre>
<p>If the HTML is:</p>
<pre><code><a href="/about">About Us</a></code></pre>
<p>the link can be located using:</p>
<pre><code>By.linkText("About Us")</code></pre>
<hr>
<h2>7. Full Link Text</h2>
<p><code>linkText()</code> requires the complete visible text of the link.</p>
<pre><code>driver.findElement(
By.linkText("Contact Us")
).click();</code></pre>
<p>If the visible text is <code>Contact Us</code>, using only <code>Contact</code> with <code>linkText()</code> will not normally match the complete text.</p>
<hr>
<h2>8. Partial Link Text</h2>
<p><code>partialLinkText()</code> can be used when only a portion of the link text is known.</p>
<pre><code>driver.findElement(
By.partialLinkText("Contact")
).click();</code></pre>
<p>For a link such as:</p>
<pre><code><a href="/contact">Contact Our Team</a></code></pre>
<p><code>partialLinkText("Contact")</code> can locate the link.</p>
<hr>
<h2>9. Link Text vs Partial Link Text</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Feature</th><th>linkText()</th><th>partialLinkText()</th></tr>
<tr><td>Matching</td><td>Complete visible text</td><td>Part of visible text</td></tr>
<tr><td>Precision</td><td>Usually higher</td><td>Can match multiple links</td></tr>
<tr><td>Usage</td><td>Stable complete text</td><td>Long or partially known text</td></tr>
<tr><td>Risk</td><td>Text changes can break locator</td><td>Ambiguous partial text can match wrong element</td></tr>
</table>
<hr>
<h2>10. Locating Links Using ID</h2>
<p>If the anchor has a unique ID, Selenium can locate it using <code>By.id()</code>.</p>
<pre><code><a id="aboutLink" href="/about">About Us</a></code></pre>
<pre><code>driver.findElement(
By.id("aboutLink")
).click();</code></pre>
<hr>
<h2>11. Locating Links Using Name</h2>
<p>If a link contains a suitable <code>name</code> attribute, Selenium can use it.</p>
<pre><code><a name="about" href="/about">About Us</a></code></pre>
<pre><code>driver.findElement(
By.name("about")
).click();</code></pre>
<hr>
<h2>12. Locating Links Using Class Name</h2>
<pre><code><a class="menu-link" href="/about">About Us</a></code></pre>
<pre><code>driver.findElement(
By.className("menu-link")
).click();</code></pre>
<p>Class names should be used carefully when many links share the same class.</p>
<hr>
<h2>13. Locating Links Using Tag Name</h2>
<p>All HTML hyperlinks generally use the <code><a></code> tag.</p>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));</code></pre>
<p>This is particularly useful when retrieving all links from a page.</p>
<hr>
<h2>14. Locating Links Using CSS Selector</h2>
<pre><code>driver.findElement(
By.cssSelector("a[href='/about']")
).click();</code></pre>
<hr>
<h2>15. CSS Selector Using ID</h2>
<pre><code>driver.findElement(
By.cssSelector("#aboutLink")
).click();</code></pre>
<hr>
<h2>16. CSS Selector Using Class</h2>
<pre><code>driver.findElement(
By.cssSelector("a.menu-link")
).click();</code></pre>
<hr>
<h2>17. CSS Selector Using href</h2>
<pre><code>driver.findElement(
By.cssSelector("a[href='/about']")
).click();</code></pre>
<hr>
<h2>18. CSS Selector Using Partial href</h2>
<p>The <code>*=</code> operator can locate elements where an attribute contains specific text.</p>
<pre><code>driver.findElement(
By.cssSelector("a[href*='about']")
).click();</code></pre>
<hr>
<h2>19. CSS Selector Using Starts With</h2>
<p>The <code>^=</code> operator matches an attribute beginning with specific text.</p>
<pre><code>driver.findElement(
By.cssSelector("a[href^='/product']")
).click();</code></pre>
<hr>
<h2>20. CSS Selector Using Multiple Attributes</h2>
<pre><code>driver.findElement(
By.cssSelector(
"a.menu-link[href='/about']"
)
).click();</code></pre>
<hr>
<h2>21. Locating Links Using XPath</h2>
<p>XPath is one of the most commonly used strategies for locating links, especially dynamic links or links based on relationships.</p>
<pre><code>driver.findElement(
By.xpath("//a[@href='/about']")
).click();</code></pre>
<hr>
<h2>22. XPath Using Link Text</h2>
<pre><code>driver.findElement(
By.xpath("//a[text()='About Us']")
).click();</code></pre>
<hr>
<h2>23. XPath Using Contains Text</h2>
<pre><code>driver.findElement(
By.xpath("//a[contains(text(),'About')]")
).click();</code></pre>
<hr>
<h2>24. XPath Using Contains href</h2>
<pre><code>driver.findElement(
By.xpath("//a[contains(@href,'about')]")
).click();</code></pre>
<hr>
<h2>25. XPath Using Starts-With</h2>
<pre><code>driver.findElement(
By.xpath("//a[starts-with(@href,'/product')]")
).click();</code></pre>
<hr>
<h2>26. XPath Using Multiple Attributes</h2>
<pre><code>driver.findElement(
By.xpath(
"//a[@class='menu-link' and @href='/about']"
)
).click();</code></pre>
<hr>
<h2>27. XPath Using Parent Element</h2>
<pre><code>driver.findElement(
By.xpath(
"//nav[@class='main-menu']//a[text()='Home']"
)
).click();</code></pre>
<hr>
<h2>28. XPath Using Following Relationship</h2>
<pre><code>driver.findElement(
By.xpath(
"//span[text()='Products']/following::a[1]"
)
).click();</code></pre>
<hr>
<h2>29. XPath Using Position</h2>
<pre><code>driver.findElement(
By.xpath("(//a[@class='menu-link'])[2]")
).click();</code></pre>
<p>Position-based XPath should be used carefully because changes in page structure can change the matching element.</p>
<hr>
<h2>30. click() Method</h2>
<p>The <code>click()</code> method performs a click operation on a link.</p>
<pre><code>driver.findElement(
By.linkText("Home")
).click();</code></pre>
<hr>
<h2>31. isDisplayed()</h2>
<p><code>isDisplayed()</code> checks whether the link is visible on the page.</p>
<pre><code>WebElement link = driver.findElement(
By.linkText("Home")
);
if (link.isDisplayed()) {
System.out.println("Link is visible");
}</code></pre>
<hr>
<h2>32. isEnabled()</h2>
<p><code>isEnabled()</code> checks whether the link is enabled.</p>
<pre><code>if (link.isEnabled()) {
System.out.println("Link is enabled");
}</code></pre>
<hr>
<h2>33. Complete Link State Validation</h2>
<pre><code>WebElement link = driver.findElement(
By.linkText("About Us")
);
if (link.isDisplayed() && link.isEnabled()) {
System.out.println(
"Link is visible and enabled"
);
}</code></pre>
<hr>
<h2>34. Click Only if Link Is Displayed</h2>
<pre><code>WebElement link = driver.findElement(
By.linkText("Contact Us")
);
if (link.isDisplayed()) {
link.click();
}</code></pre>
<hr>
<h2>35. Verify Link Text</h2>
<pre><code>String actualText = driver.findElement(
By.id("aboutLink")
).getText();
System.out.println(actualText);</code></pre>
<hr>
<h2>36. Verify Link Text Using Assertion</h2>
<pre><code>String actualText = driver.findElement(
By.id("aboutLink")
).getText();
Assert.assertEquals(
actualText,
"About Us"
);</code></pre>
<hr>
<h2>37. Get Link URL</h2>
<p>The destination URL can be retrieved using the <code>href</code> attribute.</p>
<pre><code>String href = driver.findElement(
By.linkText("About Us")
).getAttribute("href");
System.out.println(href);</code></pre>
<hr>
<h2>38. Verify Link URL</h2>
<pre><code>String href = driver.findElement(
By.linkText("About Us")
).getAttribute("href");
Assert.assertEquals(
href,
"https://example.com/about"
);</code></pre>
<hr>
<h2>39. Internal Links</h2>
<p>Internal links navigate within the same website or application.</p>
<pre><code><a href="/products">Products</a></code></pre>
<p>Automation can click the link and verify the resulting URL or page title.</p>
<pre><code>driver.findElement(
By.linkText("Products")
).click();
Assert.assertTrue(
driver.getCurrentUrl().contains("/products")
);</code></pre>
<hr>
<h2>40. External Links</h2>
<p>External links navigate to another domain.</p>
<pre><code><a href="https://www.example.com">
Example
</a></code></pre>
<p>Automation can verify the <code>href</code> before clicking or verify the destination after navigation.</p>
<hr>
<h2>41. Relative URL vs Absolute URL</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Type</th><th>Example</th></tr>
<tr><td>Relative URL</td><td><code>/about</code></td></tr>
<tr><td>Absolute URL</td><td><code>https://example.com/about</code></td></tr>
</table>
<hr>
<h2>42. target="_blank"</h2>
<p>A link with <code>target="_blank"</code> commonly opens its destination in a new tab or browsing context.</p>
<pre><code><a href="https://example.com"
target="_blank">
Open Example
</a></code></pre>
<hr>
<h2>43. Handling Links That Open New Tabs</h2>
<pre><code>String parentWindow =
driver.getWindowHandle();
driver.findElement(
By.linkText("Open Example")
).click();
Set<String> windows =
driver.getWindowHandles();
for (String window : windows) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}</code></pre>
<hr>
<h2>44. Verify New Tab URL</h2>
<pre><code>String currentUrl = driver.getCurrentUrl();
System.out.println(
"New tab URL: " + currentUrl
);</code></pre>
<hr>
<h2>45. Switch Back to Parent Window</h2>
<pre><code>driver.switchTo().window(parentWindow);</code></pre>
<hr>
<h2>46. Opening a Link in a New Window</h2>
<p>The exact browser behavior of a link depends on the browser and HTML/application implementation. Selenium can handle the resulting window or tab using window handles.</p>
<pre><code>String originalWindow =
driver.getWindowHandle();
driver.findElement(
By.linkText("Open Report")
).click();
for (String windowHandle :
driver.getWindowHandles()) {
if (!windowHandle.equals(originalWindow)) {
driver.switchTo().window(windowHandle);
break;
}
}</code></pre>
<hr>
<h2>47. Download Links</h2>
<p>Some links start a file download instead of navigating to a new page.</p>
<pre><code><a href="/files/report.pdf">
Download Report
</a></code></pre>
<p>Selenium can click the link:</p>
<pre><code>driver.findElement(
By.linkText("Download Report")
).click();</code></pre>
<p>File-download validation usually requires browser download configuration and filesystem verification in addition to Selenium.</p>
<hr>
<h2>48. Download Link href Validation</h2>
<pre><code>String href = driver.findElement(
By.linkText("Download Report")
).getAttribute("href");
Assert.assertTrue(
href.endsWith(".pdf")
);</code></pre>
<hr>
<h2>49. Mailto Links</h2>
<p>Websites may use <code>mailto:</code> links to launch an email application.</p>
<pre><code><a href="mailto:[email protected]">
Email Support
</a></code></pre>
<p>Selenium can verify the <code>href</code> without necessarily launching the local email application.</p>
<pre><code>String href = driver.findElement(
By.linkText("Email Support")
).getAttribute("href");
Assert.assertTrue(
href.startsWith("mailto:")
);</code></pre>
<hr>
<h2>50. Telephone Links</h2>
<p>Mobile-friendly websites may use <code>tel:</code> links.</p>
<pre><code><a href="tel:+919987184296">
Call Us
</a></code></pre>
<p>The link can be validated by checking its <code>href</code> attribute.</p>
<hr>
<h2>51. Anchor Links</h2>
<p>Anchor links navigate to a section of the same page.</p>
<pre><code><a href="#services">
Services
</a>
<section id="services">
Services Content
</section></code></pre>
<hr>
<h2>52. Testing Anchor Link</h2>
<pre><code>driver.findElement(
By.linkText("Services")
).click();
String url = driver.getCurrentUrl();
Assert.assertTrue(
url.contains("#services")
);</code></pre>
<hr>
<h2>53. Navigation Menu Links</h2>
<p>Navigation menus commonly contain links such as:</p>
<ul>
<li>Home</li>
<li>About</li>
<li>Services</li>
<li>Products</li>
<li>Blog</li>
<li>Contact</li>
</ul>
<pre><code>driver.findElement(
By.linkText("Products")
).click();</code></pre>
<hr>
<h2>54. Footer Links</h2>
<p>Footer sections commonly contain links to privacy policy, terms and conditions, contact pages, social profiles, and help pages.</p>
<pre><code>driver.findElement(
By.xpath("//footer//a[text()='Privacy Policy']")
).click();</code></pre>
<hr>
<h2>55. Links Inside a Table</h2>
<p>Tables may contain links for actions such as View, Edit, Delete, Details, or Download.</p>
<pre><code>driver.findElement(
By.xpath("//tr[td[text()='John']]//a[text()='View']")
).click();</code></pre>
<hr>
<h2>56. Specific Row Link</h2>
<pre><code>WebElement row = driver.findElement(
By.xpath("//tr[td[text()='Order 1001']]")
);
row.findElement(
By.linkText("View")
).click();</code></pre>
<hr>
<h2>57. Product Listing Links</h2>
<p>E-commerce websites contain product names that are commonly implemented as links.</p>
<pre><code>driver.findElement(
By.xpath("//a[contains(text(),'Laptop')]")
).click();</code></pre>
<hr>
<h2>58. Multiple Product Links</h2>
<pre><code>List<WebElement> products =
driver.findElements(
By.cssSelector(".product-card a")
);
for (WebElement product : products) {
System.out.println(product.getText());
}</code></pre>
<hr>
<h2>59. Count All Links</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println(
"Total links: " + links.size()
);</code></pre>
<hr>
<h2>60. Print All Link Texts</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
System.out.println(link.getText());
}</code></pre>
<hr>
<h2>61. Print All Link URLs</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String text = link.getText();
String href = link.getAttribute("href");
System.out.println(
text + " -> " + href
);
}</code></pre>
<hr>
<h2>62. Find Links Without href</h2>
<p>Some anchor elements may not have a destination URL.</p>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String href =
link.getAttribute("href");
if (href == null || href.isEmpty()) {
System.out.println(
"Link without href: " +
link.getText()
);
}
}</code></pre>
<hr>
<h2>63. Verify Links Are Visible</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
if (link.isDisplayed()) {
System.out.println(
"Visible: " + link.getText()
);
}
}</code></pre>
<hr>
<h2>64. Verify Link Has href</h2>
<pre><code>String href =
link.getAttribute("href");
Assert.assertNotNull(href);</code></pre>
<hr>
<h2>65. Broken Links</h2>
<p>A broken link is a hyperlink whose destination cannot be successfully reached or returns an HTTP error response such as 404. Selenium itself is primarily a browser automation tool, so broken-link validation is often performed by extracting URLs and using an HTTP client for response verification.</p>
<hr>
<h2>66. Extract All href Values</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));
for (WebElement link : links) {
String href =
link.getAttribute("href");
if (href != null) {
System.out.println(href);
}
}</code></pre>
<hr>
<h2>67. Link Verification Using HTTP Client</h2>
<p>A Java HTTP client can be used separately to request each extracted URL and inspect the response status.</p>
<pre><code>HttpClient client =
HttpClient.newHttpClient();
HttpRequest request =
HttpRequest.newBuilder(
URI.create(url)
).GET().build();
HttpResponse<String> response =
client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
System.out.println(
response.statusCode()
);</code></pre>
<hr>
<h2>68. Verify Successful HTTP Response</h2>
<pre><code>int statusCode =
response.statusCode();
if (statusCode >= 200 &&
statusCode < 400) {
System.out.println(
"Link is reachable"
);
}</code></pre>
<hr>
<h2>69. Dynamic Link</h2>
<p>Dynamic links may contain changing IDs, parameters, or generated text.</p>
<pre><code><a href="/user/12345/profile"
id="user_12345">
Profile
</a></code></pre>
<p>A stable part of the element can be used for locating it.</p>
<hr>
<h2>70. Dynamic ID Using XPath</h2>
<pre><code>driver.findElement(
By.xpath(
"//a[starts-with(@id,'user_')]"
)
).click();</code></pre>
<hr>
<h2>71. Dynamic href Using Contains</h2>
<pre><code>driver.findElement(
By.xpath(
"//a[contains(@href,'/profile')]"
)
).click();</code></pre>
<hr>
<h2>72. Dynamic Link Text</h2>
<p>If link text contains changing values, avoid exact text when the changing portion is not important.</p>
<pre><code>driver.findElement(
By.xpath(
"//a[contains(text(),'View')]"
)
).click();</code></pre>
<hr>
<h2>73. Dynamic Links in Tables</h2>
<pre><code>driver.findElement(
By.xpath(
"//tr[td[contains(text(),'John')]]" +
"//a[contains(text(),'View')]"
)
).click();</code></pre>
<hr>
<h2>74. Link Inside Modal</h2>
<pre><code>WebElement modal = driver.findElement(
By.id("detailsModal")
);
modal.findElement(
By.linkText("View Details")
).click();</code></pre>
<hr>
<h2>75. Link Inside Iframe</h2>
<p>If the link is located inside an iframe, Selenium must switch to that iframe first.</p>
<pre><code>driver.switchTo().frame("contentFrame");
driver.findElement(
By.linkText("Learn More")
).click();
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>76. Nested Iframe Link</h2>
<pre><code>driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
driver.findElement(
By.linkText("Open Details")
).click();
driver.switchTo().defaultContent();</code></pre>
<hr>
<h2>77. Link Inside Shadow DOM</h2>
<p>Modern web applications may use Shadow DOM to encapsulate components. Selenium can access supported Shadow DOM elements through the shadow root.</p>
<pre><code>WebElement host = driver.findElement(
By.cssSelector("custom-menu")
);
SearchContext shadowRoot =
host.getShadowRoot();
WebElement link = shadowRoot.findElement(
By.cssSelector("a")
);
link.click();</code></pre>
<hr>
<h2>78. Link Not Immediately Clickable</h2>
<p>A link may be present in the DOM but not immediately clickable because of page loading, animations, overlays, or asynchronous content.</p>
<pre><code>WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement link = wait.until(
ExpectedConditions.elementToBeClickable(
By.linkText("About Us")
)
);
link.click();</code></pre>
<hr>
<h2>79. Explicit Wait for Link Visibility</h2>
<pre><code>WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement link = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.linkText("About Us")
)
);</code></pre>
<hr>
<h2>80. Implicit Wait for Links</h2>
<pre><code>driver.manage().timeouts()
.implicitlyWait(
Duration.ofSeconds(10)
);</code></pre>
<p>Implicit waits apply to element searches globally. Explicit waits are usually more precise for specific navigation conditions.</p>
<hr>
<h2>81. ElementClickInterceptedException</h2>
<p>This exception can occur when another element such as an overlay, popup, cookie banner, or modal intercepts the click.</p>
<p>Possible solutions include:</p>
<ul>
<li>Wait for the overlay to disappear</li>
<li>Close the popup</li>
<li>Wait until the link is clickable</li>
<li>Scroll the element into view when appropriate</li>
<li>Review the page structure</li>
</ul>
<hr>
<h2>82. ElementNotInteractableException</h2>
<p>This exception may occur when the link exists in the DOM but cannot currently be interacted with.</p>
<pre><code>WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement link = wait.until(
ExpectedConditions.elementToBeClickable(
By.linkText("Download")
)
);
link.click();</code></pre>
<hr>
<h2>83. NoSuchElementException</h2>
<p>This exception usually indicates that Selenium could not find the element using the specified locator.</p>
<p>Check:</p>
<ul>
<li>Locator correctness</li>
<li>Page source</li>
<li>Iframe context</li>
<li>Dynamic loading</li>
<li>Shadow DOM</li>
<li>Page navigation state</li>
</ul>
<hr>
<h2>84. StaleElementReferenceException</h2>
<p>This can happen when the DOM is refreshed or modified after Selenium has stored a WebElement reference.</p>
<p>Instead of reusing the stale reference, locate the element again.</p>
<pre><code>WebElement link = driver.findElement(
By.linkText("Refresh Data")
);
link.click();
link = driver.findElement(
By.linkText("Refresh Data")
);</code></pre>
<hr>
<h2>85. Scrolling to a Link</h2>
<p>Some links may be outside the current viewport.</p>
<pre><code>WebElement link = driver.findElement(
By.linkText("Contact")
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView(true);",
link
);
link.click();</code></pre>
<hr>
<h2>86. JavaScript Click</h2>
<p>JavaScript click can sometimes help diagnose or handle unusual UI behavior, but normal Selenium interaction should be preferred whenever possible.</p>
<pre><code>WebElement link = driver.findElement(
By.linkText("Contact")
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
link
);</code></pre>
<hr>
<h2>87. When Not to Use JavaScript Click</h2>
<ul>
<li>When normal <code>click()</code> works</li>
<li>When user-like interaction is required</li>
<li>When application click events are important</li>
<li>When JavaScript would bypass UI behavior</li>
<li>When the real issue is synchronization</li>
</ul>
<hr>
<h2>88. Link Navigation Validation</h2>
<pre><code>driver.findElement(
By.linkText("Products")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(
ExpectedConditions.urlContains(
"/products"
)
);
Assert.assertTrue(
driver.getCurrentUrl().contains("/products")
);</code></pre>
<hr>
<h2>89. Verify Page Title After Clicking Link</h2>
<pre><code>driver.findElement(
By.linkText("Products")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(
ExpectedConditions.titleContains(
"Products"
)
);
Assert.assertTrue(
driver.getTitle().contains("Products")
);</code></pre>
<hr>
<h2>90. Verify Navigation Using Current URL</h2>
<pre><code>driver.findElement(
By.linkText("About Us")
).click();
String currentUrl =
driver.getCurrentUrl();
System.out.println(currentUrl);</code></pre>
<hr>
<h2>91. Verify Link Text and href Together</h2>
<pre><code>WebElement link = driver.findElement(
By.id("aboutLink")
);
String text = link.getText();
String href = link.getAttribute("href");
Assert.assertEquals(text, "About Us");
Assert.assertTrue(
href.contains("/about")
);</code></pre>
<hr>
<h2>92. TestNG Link Validation</h2>
<pre><code>@Test
public void verifyAboutLink() {
WebElement link = driver.findElement(
By.linkText("About Us")
);
Assert.assertTrue(
link.isDisplayed()
);
Assert.assertTrue(
link.isEnabled()
);
String href =
link.getAttribute("href");
Assert.assertTrue(
href.contains("/about")
);
}</code></pre>
<hr>
<h2>93. Complete TestNG Link Test</h2>
<pre><code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LinkTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://example.com");
}
@Test
public void verifyAboutLink() {
WebElement link = driver.findElement(
By.linkText("About Us")
);
Assert.assertTrue(
link.isDisplayed()
);
String href =
link.getAttribute("href");
Assert.assertNotNull(href);
link.click();
Assert.assertTrue(
driver.getCurrentUrl()
.contains("/about")
);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}</code></pre>
<hr>
<h2>94. Links Using Page Object Model</h2>
<p>Page Object Model keeps locators and page actions organized inside page classes.</p>
<pre><code>public class HomePage {
WebDriver driver;
By aboutLink =
By.linkText("About Us");
By contactLink =
By.linkText("Contact Us");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public void clickAbout() {
driver.findElement(aboutLink).click();
}
public void clickContact() {
driver.findElement(contactLink).click();
}
}</code></pre>
<hr>
<h2>95. Reusable Link Click Utility</h2>
<pre><code>public class LinkUtil {
public static void clickLink(
WebDriver driver,
By locator) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement link = wait.until(
ExpectedConditions.elementToBeClickable(
locator
)
);
link.click();
}
}</code></pre>
<hr>
<h2>96. Reusable Link Text Validation</h2>
<pre><code>public static void verifyLinkText(
WebDriver driver,
By locator,
String expectedText) {
String actualText =
driver.findElement(locator)
.getText();
Assert.assertEquals(
actualText,
expectedText
);
}</code></pre>
<hr>
<h2>97. Reusable href Validation</h2>
<pre><code>public static void verifyHref(
WebDriver driver,
By locator,
String expectedUrl) {
String actualUrl =
driver.findElement(locator)
.getAttribute("href");
Assert.assertEquals(
actualUrl,
expectedUrl
);
}</code></pre>
<hr>
<h2>98. Find All Navigation Links</h2>
<pre><code>List<WebElement> navigationLinks =
driver.findElements(
By.cssSelector("nav a")
);
for (WebElement link : navigationLinks) {
System.out.println(
link.getText()
);
}</code></pre>
<hr>
<h2>99. Count Navigation Links</h2>
<pre><code>int count =
driver.findElements(
By.cssSelector("nav a")
).size();
System.out.println(
"Navigation links: " + count
);</code></pre>
<hr>
<h2>100. Verify Expected Navigation Links</h2>
<pre><code>List<WebElement> links =
driver.findElements(
By.cssSelector("nav a")
);
for (WebElement link : links) {
String text = link.getText();
if (text.equals("Home") ||
text.equals("About Us") ||
text.equals("Contact Us")) {
System.out.println(
"Expected link found: " + text
);
}
}</code></pre>
<hr>
<h2>101. Links in a Login Workflow</h2>
<p>Login pages frequently contain links such as Forgot Password, Register, Terms, Privacy Policy, and Help.</p>
<pre><code>driver.findElement(
By.linkText("Forgot Password")
).click();</code></pre>
<hr>
<h2>102. Registration Link</h2>
<pre><code>driver.findElement(
By.linkText("Create Account")
).click();</code></pre>
<hr>
<h2>103. Forgot Password Link</h2>
<pre><code>driver.findElement(
By.partialLinkText("Forgot")
).click();</code></pre>
<hr>
<h2>104. Terms and Conditions Link</h2>
<pre><code>WebElement terms = driver.findElement(
By.xpath(
"//a[contains(text(),'Terms')]"
)
);
terms.click();</code></pre>
<hr>
<h2>105. Privacy Policy Link</h2>
<pre><code>driver.findElement(
By.linkText("Privacy Policy")
).click();</code></pre>
<hr>
<h2>106. Link Validation Checklist</h2>
<ul>
<li>Verify link exists.</li>
<li>Verify link is displayed.</li>
<li>Verify link is enabled.</li>
<li>Verify link text.</li>
<li>Verify href.</li>
<li>Click the link.</li>
<li>Verify destination URL.</li>
<li>Verify destination page title.</li>
<li>Verify new tab or window when applicable.</li>
<li>Verify download behavior when applicable.</li>
<li>Verify external links when applicable.</li>
<li>Verify broken links when required.</li>
</ul>
<hr>
<h2>107. Common Mistakes While Handling Links</h2>
<ul>
<li>Using unstable XPath expressions</li>
<li>Using partial link text when several links match</li>
<li>Ignoring iframe context</li>
<li>Ignoring dynamic content</li>
<li>Not waiting for clickable state</li>
<li>Not validating the destination</li>
<li>Assuming every anchor navigates to a new page</li>
<li>Using JavaScript unnecessarily</li>
<li>Not handling new tabs</li>
<li>Not checking the href attribute</li>
</ul>
<hr>
<h2>108. Bad Locator Example</h2>
<pre><code>driver.findElement(
By.xpath("(//a)[7]")
).click();</code></pre>
<p>This locator depends on the seventh anchor in the DOM and can easily break when the page structure changes.</p>
<hr>
<h2>109. Better Locator Example</h2>
<pre><code>driver.findElement(
By.xpath("//a[text()='Contact Us']")
).click();</code></pre>
<p>A meaningful text-based locator is easier to understand and maintain when the text is stable.</p>
<hr>
<h2>110. Best Locator Strategy</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Locator</th><th>Use When</th></tr>
<tr><td>ID</td><td>Unique and stable ID exists</td></tr>
<tr><td>Link Text</td><td>Complete visible link text is stable</td></tr>
<tr><td>Partial Link Text</td><td>Only part of text is stable and unique</td></tr>
<tr><td>CSS</td><td>Stable attributes or classes exist</td></tr>
<tr><td>XPath</td><td>Complex relationships or dynamic attributes must be handled</td></tr>
</table>
<hr>
<h2>111. Best Practices for Link Automation</h2>
<ol>
<li>Prefer stable locators.</li>
<li>Use <code>linkText()</code> when complete text is stable.</li>
<li>Use <code>partialLinkText()</code> only when the partial text uniquely identifies the link.</li>
<li>Prefer CSS selectors for simple attribute-based locations.</li>
<li>Use XPath for complex relationships.</li>
<li>Use explicit waits for dynamically loaded links.</li>
<li>Validate both link text and href where required.</li>
<li>Handle new tabs using window handles.</li>
<li>Switch to iframes before interacting with links inside them.</li>
<li>Use Page Object Model for maintainability.</li>
<li>Create reusable utilities for repeated link operations.</li>
<li>Avoid unnecessary JavaScript.</li>
</ol>
<hr>
<h2>112. Real-World E-Commerce Project</h2>
<p>Create a Selenium automation project for an e-commerce application containing:</p>
<ul>
<li>Home page links</li>
<li>Category links</li>
<li>Product links</li>
<li>Cart link</li>
<li>Checkout link</li>
<li>Account links</li>
<li>Help links</li>
</ul>
<p>Test flow:</p>
<ol>
<li>Open the home page.</li>
<li>Verify navigation links.</li>
<li>Click a product category.</li>
<li>Verify the category URL.</li>
<li>Click a product.</li>
<li>Verify product details page.</li>
<li>Add product to cart.</li>
<li>Navigate to cart.</li>
<li>Continue to checkout.</li>
<li>Verify the final page.</li>
</ol>
<hr>
<h2>113. Real-World Banking Project</h2>
<p>Automate links in a banking application such as:</p>
<ul>
<li>Accounts</li>
<li>Transactions</li>
<li>Statements</li>
<li>Loans</li>
<li>Cards</li>
<li>Profile</li>
<li>Support</li>
<li>Logout</li>
</ul>
<p>Verify that every navigation link opens the correct section.</p>
<hr>
<h2>114. Real-World News Website Project</h2>
<p>Automate links for:</p>
<ul>
<li>Home</li>
<li>Politics</li>
<li>Business</li>
<li>Technology</li>
<li>Sports</li>
<li>Entertainment</li>
<li>Article links</li>
<li>Author links</li>
<li>Category links</li>
</ul>
<p>Verify navigation and article URLs using Selenium.</p>
<hr>
<h2>115. Interview Question: How Do You Handle Links in Selenium?</h2>
<p>Links can be handled using Selenium locators such as <code>linkText</code>, <code>partialLinkText</code>, XPath, CSS Selector, ID, and other locator strategies. After locating the link, Selenium's <code>click()</code> method can be used to interact with it.</p>
<hr>
<h2>116. Interview Question: What Is the Difference Between linkText and partialLinkText?</h2>
<p><code>linkText()</code> searches for the complete visible link text, while <code>partialLinkText()</code> searches using a portion of the visible link text.</p>
<hr>
<h2>117. Interview Question: How Do You Get All Links on a Page?</h2>
<pre><code>List<WebElement> links =
driver.findElements(By.tagName("a"));</code></pre>
<hr>
<h2>118. Interview Question: How Do You Count All Links?</h2>
<pre><code>int count =
driver.findElements(
By.tagName("a")
).size();
System.out.println(count);</code></pre>
<hr>
<h2>119. Interview Question: How Do You Get the URL of a Link?</h2>
<pre><code>String href = driver.findElement(
By.linkText("About Us")
).getAttribute("href");</code></pre>
<hr>
<h2>120. Interview Question: How Do You Handle a Link Opening in a New Tab?</h2>
<p>Store the current window handle, click the link, retrieve all window handles, identify the new handle, and switch to it using <code>driver.switchTo().window()</code>.</p>
<hr>
<h2>121. Interview Question: What If a Link Is Not Clickable?</h2>
<p>Check whether the link is displayed and enabled, inspect overlays, verify iframe context, wait for the element to become clickable, and confirm that the locator identifies the correct element.</p>
<hr>
<h2>122. Interview Question: How Do You Handle Dynamic Links?</h2>
<p>Use stable attributes or dynamic XPath expressions such as <code>contains()</code> and <code>starts-with()</code>. Avoid relying on dynamically generated IDs or positions whenever possible.</p>
<hr>
<h2>123. Interview Question: How Do You Handle Links Inside an Iframe?</h2>
<p>Switch to the iframe first using <code>driver.switchTo().frame()</code>, interact with the link, and then return to the main document using <code>driver.switchTo().defaultContent()</code>.</p>
<hr>
<h2>124. Interview Question: How Do You Validate a Broken Link?</h2>
<p>Extract the link's <code>href</code> attribute and use an HTTP client to send a request to the URL. The response status code can then be evaluated to determine whether the URL is reachable.</p>
<hr>
<h2>125. Practical Link Automation Checklist</h2>
<table border="1" cellpadding="8" cellspacing="0">
<tr><th>Area</th><th>Validation</th></tr>
<tr><td>Presence</td><td>Link exists on the page</td></tr>
<tr><td>Visibility</td><td>Link is displayed</td></tr>
<tr><td>Enabled</td><td>Link can be interacted with</td></tr>
<tr><td>Text</td><td>Visible text is correct</td></tr>
<tr><td>href</td><td>Destination URL is correct</td></tr>
<tr><td>Click</td><td>Click operation works</td></tr>
<tr><td>Navigation</td><td>Correct destination opens</td></tr>
<tr><td>New tab</td><td>Correct window is handled</td></tr>
<tr><td>External link</td><td>External destination is correct</td></tr>
<tr><td>Download</td><td>Expected file download occurs</td></tr>
<tr><td>Dynamic link</td><td>Stable dynamic locator works</td></tr>
<tr><td>Iframe</td><td>Correct frame context is used</td></tr>
</table>
<hr>
<h2>126. Conclusion</h2>
<p>Links are fundamental web elements and are involved in almost every web application navigation workflow. Selenium WebDriver provides multiple ways to locate and interact with links, including <code>linkText()</code>, <code>partialLinkText()</code>, ID, CSS Selector, XPath, and tag name.</p>
<p>Effective link automation requires more than simply clicking an anchor. A robust Selenium test should verify the link's visibility, enabled state, text, href, destination URL, page title, new tab behavior, download behavior, and dynamic loading where applicable. Advanced scenarios such as iframes, Shadow DOM, dynamic links, overlays, and new windows require appropriate Selenium techniques and synchronization.</p>
<p>For organized Selenium automation training covering WebDriver, locators, web elements, TestNG, data-driven testing, Page Object Model, automation frameworks, and real-time projects, visit the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a>.</p>
<p>For course demo registration, visit the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a> page.</p>
</div>