Summary -
In this topic, we described about the below sections -
Tag name locator strategy is like ID locator strategy. However, we use name attribute instead of ID attribute.
This is an effective way to locate an element with a name attribute. There is no standard for uniqueness of the name attribute on a web page and multiple elements can have same name. If multiple name attibute elements exists, then the first matching element pickup for testing. If no element has a matching name attribute, then NoSuchElementException will be raised.
We can add filters to refine the locator. There are two filter types - value and index.
Pros
- Works with fixed list of similar elements.
Cons
- Difficult to use with data-bound lists.
Example
Now, let’s understand the working of tag name locator with the help of a simple example. We will launch Chrome and navigate to bing.com. Here, we will try to locate the search box using name Locator.
On inspecting the above web element, we can see an input tag has attribute name. Now, I will use the value of name locator i.e."q" to perform search.
Let’s see how the automation of the search look like in Selenium IDE that send value "India" to the search box using name locator.
The java program for the above test is -
// Generated by Selenium IDEis
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNot.not;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Keys;
import java.util.*;
import java.net.MalformedURLException;
import java.net.URL;
public class LocatorsTest {
private WebDriver driver;
private Map<String, Object> vars;
JavascriptExecutor js;
@Before
public void setUp() {
driver = new ChromeDriver();
js = (JavascriptExecutor) driver;
vars = new HashMap();
}
@After
public void tearDown() {
driver.quit();
}
@Test
public void locators() {
driver.get("https://www.bing.com/");
driver.manage().window().setSize(new Dimension(1098, 638));
driver.findElement(By.name("q")).sendKeys("india");
driver.findElement(By.cssSelector(".sa_tmHS")).click();
}
}
When you run the java program,Chrome driver launches chrome,redirect to bing search page, enter the search key word as "india" and navigate to search results page. Refer the below image for the output -
The above example gives a clear understanding of how name locator in Selenium works.