
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Element Using Attribute Name in Selenium
We can find an element using the attribute name with Selenium webdriver using the locators - name, css, or xpath. To identify the element with css, the expression should be tagname[name='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@name='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator name, we have to use the By.name method.
Let us look at the html code of an element with name attribute −
Syntax
WebElement e = driver. findElement(By.name("q")); WebElement m = driver. findElement(By.xpath("//input[@name = 'q']")); WebElement n = driver. findElement(By.cssSelector("input[name='q']"));
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LocatorName{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.google.com/"); // identify element with name WebElement k = driver.findElement(By.name("q")); k.sendKeys("Selenium"); //identify element with css WebElement p = driver. findElement(By.cssSelector("input[name='q']")); String st = p.getAttribute("value"); System.out.println("Attribute value: " + st); //identify element with xpath WebElement o = driver. findElement(By.xpath("//input[@name='q']")); o.clear(); driver.quit(); } }
Output
Advertisements