Find element by name selenium
Selenium find element by name is also another popular way to locate element. It uses name attribute of element to find element by name in selenium. Also it is easy for selenium to find name of element. Most of the time you will find name of element on page.
Expression to find element by name in selenium is : findElement(By.name("name value of element")).
How to find name of element?
You can find name of element using developer tool in google chrome browser. Here are the steps to find name of element using developer tool.
- Open google chrome browser.
- Open targeted page in browser.
- Right click on element and inspect it. It will open developer tool with element's html selectionas shown in below given image.
Here, name attribute's value is fname for First Name textbox. You can use that value in test script to locate element by name in selenium as below. You can find element by name in selenium as below.
- WebElement fNameTxt= driver.findElement(By.name("fname"));
Above give syntax will search for element with name attribute value fname and locate it if element present on page.
Below given syntax will type your desired text i.e. "my name" in textbox.
- fNameTxt.sendKeys("test text");
When not to use find element by name in selenium?
You should use find element by name in selenium only if value of name attribute is static. If it is changing on every page reload then you should not use find element by name.
If you have used selenium find element by name and element with specified name not found on page then it will break your test script execution and raise org.openqa.selenium.NoSuchElementException exception if selected element not found on page.
Selenium find element by name example
Example of selenium find element by name
import org.openqa.selenium.By;
public class FindByName{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.navigate().to("http://only-testing-blog.blogspot.com/2013/09/testing.html");
//selenium find by name.
WebElement fNameTxt= driver.findElement(By.name("fname"));
fNameTxt.sendKeys("my name");
driver.close();
}
}
Above given example will find element by name fname and type text my name in it.
No comments:
Post a Comment