This post was most recently updated on June 14th, 2019
Locator Type: Name
- Name attribute is unique throughout html document except checkbox and radio button.
- Name attribute is not unique if multiple radio button and checkboxes used with same name.
- Name attribute used with iframe which can be used to switch driver from current web page to iframe by using name.
Java code to find web element using name attribute value.
WebElement wElement=driver.findElement(By.name("Name_Attribute_Value"));
- Go to www.google.com,
- Inspect search box
- Find the value of name attribute.
Java code to find above element by name attribute is:
WebElement searchInputBox=driver.findElement(By.name("q"));
Sample selenium code that uses name locator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class SeleniumMain { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "D:/Automation/chromedriver.exe"); WebDriver driver; ChromeOptions cOptions=new ChromeOptions(); cOptions.addArguments("--start-maximized"); driver=new ChromeDriver(cOptions); driver.get("https://www.google.com"); driver.manage().timeouts().pageLoadTimeout(500, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); driver.manage().window().maximize(); WebElement searchBoxWElement; searchBoxWElement=driver.findElement(By.name("q")); searchBoxWElement.sendKeys("Selenium Locator by Name"); } } |