Finding links

Selenium WebDriver provides two special methods to find links on a page. Links can be searched either by their text or by partial text.

Finding links with partial text comes in handy when links have dynamic text. In this recipe, we will see how to use these methods to find links.

How to do it...

Let's create a simple test to see how finding links works in Selenium WebDriver with the following options.

Finding a link by its text

Selenium WebDriver's By class provides the linkText() method to locate links using text displayed for the link. In the following example, we will locate the Gmail link displayed on the Google Home page:

WebElement gmailLink = driver.findElement(By.linkText("GMail")); assertEquals("http://mail.google.com/", gmailLink.getAttribute("href")); ...

Get Selenium Testing Tools Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.