Working With Links using Selenium WebDriver
Links in HTML are nothing but hyperlinks. When we click on a link, we are navigated to another page or document.
HTML links are defined with anchor (<a>) tags.
Syntax: <a href=”url”> link text </a>
Example:
<a href="http://qatechhub.com/selenium/">Selenium Tutorial</a>
Here in above code, “href“ is an attribute which specifies the address of another HTML page and “Selenium Tutorial” is the link text associated with it. (i.e. the visible part on the page).
Identifiers in Selenium WebDriver to Interact with Links:
Selenium WebDriver provides two different identifiers to interact with links.
- linktext()
- partialLinktext()
linktext() identifier matches exact text associated with the link web element. So, to click on above-mentioned link code will be:
driver.findElement(By.linkText("Selenium Tutorial")).click();
partialLinktext() identifier matches partial text associated with the link web element. It can be considered as a contains method. So, to click on above-mentioned link code will be:
Driver.findElement(By.partialLinkText("Selenium")).click(); //or Driver.findElement(By.partialLinkText("Tutorial")).click();
Actions performed on Links:
We can perform different actions on a link like click(), getText(), moverHover().
The click() method is to click on the mentioned link, this will navigate you to another webpage in the same window or in another window.
driver.findElement(By.linkText("Selenium Tutorial")).click();
The getText() method is to fetch the text from a link. Below code will return “Selenium Tutorial”.
driver.findElement(By.partialLinkText("Tutorial")).getText();
The mouseHover() operation we will learn in detail in later classes.
Getting Attribute from an HTML Tag:
One of the important scenario while working with links is to get the URL from the link. getAttribute(“String”) method is used to get the url from the link. See the below example, for above HTML link the code will return “http://qatechub.com/selenium”.
String url = driver.findElement(By.linkText("Selenium Tutorial")).getAttribute("href");
Let us try some interview based scenarios:
Scenario 1: Counting numbers of link on a web page say Flipkart
- Open any browser say “Chrome”
- Navigate to Flipkart website. (http://www.flipkart.com)
- Write a code to get the number of links on this page.
To get the number of links on a page, we will first get all the links using a method called findElements(By.tagName(“a”)). This method will return a list of all the WebElements in a list. Call size() method to get the count of the number of WebElements i.e. number of links.
package day3; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class WorkingWithLinks { WebDriver driver; String sUrl = "http://www.flipkart.com"; public void invokeBrowser(String driver){ if(driver.equalsIgnoreCase("ff")){ oBrowser = new FirefoxDriver(); } else if(driver.equalsIgnoreCase("chrome")){ System.setProperty("webdriver.chrome.driver", "C:\\workspace\\libs\\chromedriver.exe"); oBrowser = new ChromeDriver(); } else if(driver.equalsIgnoreCase("ie")){ System.setProperty("webdriver.ie.driver", "C:\\workspace\\libs\\IEDriverServer.exe"); oBrowser = new InternetExplorerDriver(); } else { System.err.println("Invalid Browser type.. setting default browser as Firefox Driver"); driver = new FirefoxDriver(); } // To Maximize the window driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.get(sUrl); } public void getNumberOfLinks(){ int iNumberOfLinks = driver.findElements(By.tagName("a")).size(); System.out.println("Number of Links on a page : "+ iNumberOfLinks); } public void closeBrowser(){ driver.quit(); } }
To Execute the code let us create a main method:
package day3; public class DemoWorkingWithLinks { public static void main(String[] args) { WorkingWithLinks wl = new WorkingWithLinks(); wl.invokeBrowser("chrome"); wl.numberOfLinks(); } }
In above code, getNumberOfLinks() method is used to get the number of links from a page.
Scenario 2: Printing the text associated with all the links and their URL on a page say Flipkart.
- Open any browser say “Chrome.”
- Navigate to Flipkart site (http://www.flipkart.com)
- Write a code to get the number of links on this page.
- Write a code to get the text associated with each link and its URL.
This scenario is an extension of the above scenario. Here, after finding the number of links. We will iterate over each link and fetch its text using a method called getText() and fetch its URL by a method called getAttribute(“href”).
Refer below code for the same:
package day3; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class WorkingWithLinks { WebDriver driver; String sUrl = "http://www.flipkart.com"; public void invokeBrowser(String sBrowserType){ if(sBrowserType.equalsIgnoreCase("ff")){ driver = new FirefoxDriver(); } else if(sBrowserType.equalsIgnoreCase("chrome")){ System.setProperty("webdriver.chrome.driver", "C:\\workspace\\libs\\chromedriver.exe"); driver = new ChromeDriver(); } else if(sBrowserType.equalsIgnoreCase("ie")){ System.setProperty("webdriver.ie.driver", "C:\\workspace\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); } else { System.err.println("Invalid Browser type.. setting default browser as Firefox Driver"); driver = new FirefoxDriver(); } // To Maximize the window driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.get(sUrl); } public void numberOfLinks(){ int iNumberOfLinks = driver.findElements(By.tagName("a")).size(); System.out.println("Number of Links on a page : "+ iNumberOfLinks); } public void printAllLinks(){ List<WebElement> oList; oList = driver.findElements(By.tagName("a")); // OR // oList = oBrowser.findElements(By.xpath("//a")); // -- you can use xpath also for(WebElement oTemp : oList){ System.out.println("The Link Text of WebElement : "+ oTemp.getText() + " and its url is " + oTemp.getAttribute("href")); System.out.println("***********************************************"); } } public void closeBrowser(){ driver.close(); } }
Enhanced for loop is used to iterate over each link, fetching its text and associated url.
This is all in this tutorial, I hope you enjoyed the different scenario’s possible with links using Selenium WebDriver.
For any questions, queries or comments feel free to write us at support@qatechhub.com or saurabh@qatechub.com. Happy Learning 🙂