Locating GUI Elements in selenium WebDriver
Locating GUI Elements
Locating elements in WebDriver is done by using the "findElement(By.locator())"
method. The "locator" part of the code is same as any of the locators
previously discussed in the Selenium IDE chapters of these tutorials. Infact,
it is recommended that you locate GUI elements using IDE and once successfully
identified export the code to webdriver.
Here is a sample code that locates an element by its id.
Facebook is used as the Base URL.
package newproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PG2 {
public static void
main(String[] args) {
System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
WebDriver driver = new
FirefoxDriver();
String baseUrl
= "http://www.facebook.com";
String tagName
= "";
driver.get(baseUrl);
tagName =
driver.findElement(By.id("email")).getTagName();
System.out.println(tagName);
driver.close();
System.exit(0);
}
}
We used the getTagName() method to extract
the tag name of that particular element whose id is "email". When
run, this code should be able to correctly identify the tag name
"input" and will print it out on Eclipse's Console window.

Summary for locating elements
Variation
|
Description
|
Sample
|
By.className
|
finds elements based on the value of the "class"
attribute
|
findElement(By.className("someClassName"))
|
By.cssSelector
|
finds elements based on the driver's underlying CSS
Selector engine
|
findElement(By.cssSelector("input#email"))
|
By.id
|
locates elements by the value of their "id"
attribute
|
findElement(By.id("someId"))
|
By.linkText
|
finds a link element by the exact text it displays
|
findElement(By.linkText("REGISTRATION"))
|
By.name
|
locates elements by the value of the "name"
attribute
|
findElement(By.name("someName"))
|
By.partialLinkText
|
locates elements that contain the given link text
|
findElement(By.partialLinkText("REG"))
|
By.tagName
|
locates elements by their tag name
|
findElement(By.tagName("div"))
|
By.xpath
|
locates elements via XPath
|
findElement(By.xpath("//html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/
form/table/tbody/tr[5]"))
|
Comments
Post a Comment