
Selenium Assignment – 3
Here is the third assignment in the series of real-time scenarios to practice. In this assignment, we are focusing on working with links and getAttribute() method.
Number of Links on a Page:
Scenario:
- Open a Browser (write the generic code such that by changing the parameter browser can be changed.)
- Navigate to https://flipkart.com website.
- Write a method to find the count (number of) links on the homepage of Flipkart.
- Write another method to print link text and URLs of all the links on the page of Flipkart.
Try this.
package com.test.traveltest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Assignment3 {
WebDriver driver;
String flipkartUrl = "https://www.flipkart.com";
@BeforeClass
public void invokeBrowser(){
System.setProperty("webdriver.gecko.driver",
"D:\\Selenium\\geckodriver-v0.31.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(90, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
driver.get(flipkartUrl);
}
@Test
public void getLinkCount(){
List<WebElement> allLink = driver.findElements(By.tagName("a"));
System.out.println("Number of links on a page :: "+allLink.size());
}
@Test
public void getLinkUrl(){
String url = driver.findElement(By.linkText("Amazon Pay")).getAttribute("href");
System.out.println("Url :: "+ url);
}
@Test
public void getAllLinkInfo(){
List<WebElement> allLink = driver.findElements(By.tagName("a"));
for(WebElement link:allLink){
System.out.println("Link Text :: "+ link.getText());
System.out.println("Link URL :: "+ link.getAttribute("href"));
System.out.println("-------------------------------------------");
}
}
@AfterTest
public void testComplete() {
driver.close();
}
}