Locators for selenium | tagName locator example | display anchor tag "a" texts and images alternative texts for amazon india website using java-selenium

Sadakar Pochampalli
JasperSoft BI Suite Tutorials - Sadakar Pochampalli )

Hi,

In this post, you will see demonstration of "tagName" locator usage. 

"tagName"  is one of the 8 locators supported by selenium.

For instance, display all the anchors "a" or "images" alternative texts on amazaon india page   @ https://www.amazon.in/

selenium identifies the "a" and "image" tags with the following java statements.

List<WebElement> links = driver.findElements(By.tagName("a"));
List<WebElement> images = driver.findElements(By.tagName("img"));

tagNameLocatorDemo.java
package selenium.locators.examples;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class tagNameLocatorDemo {

public static void main(String[] args) {

WebDriver driver
;

System
.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
System
.setProperty("webdriver.chrome.silentOutput", "true");

driver
= new ChromeDriver();

driver
.navigate().to("https://www.amazon.in/");
driver
.manage().window().maximize();

// storing anchor - a tags in links List<WebElement> variable
List
<WebElement> links = driver.findElements(By.tagName("a"));

// printing the size of list
System
.out.println("Size of list="+links.size());

// print the top 5 Text of anchors
System
.out.println("-- Printing top 5 anchors text--");
for(int i=0;i<links.size();i++) {
System
.out.println(links.get(i).getText());
if(i==4)
break;
}
System
.out.println("------------------------------------");

// storing images - img tags in images List<WebElement> variable
List
<WebElement> images = driver.findElements(By.tagName("img"));

// foreach loop with WebElements
// if wants to break the loop on a particular index go with regular loop
System
.out.println("-- Printing images alternative texts --");
for(WebElement w2 : images) {
System
.out.println(w2.getAttribute("alt"));
}

}
}

Watch this ~ 1.5 min video for end-to-end example execution



Feedback
randomness