Element Locators in Selenium

Element Locators in Selenium
 

Selenium WebDriver uses 8 element locators (id, name, className, tagName, linkText, partialLinkText, cssSelector, xpath) to find elements on Web pages.

Why we need to use different locators?
 

i) Developers may not provide all locators for all elements

ii) Some locators may be duplicated.

So we have to choose any one unique locator to recognize the element.

How to inspect elements?
Download and install Firebug and Firepath plug ins/Add ons for Firefox Browser. If it Internet Explorer or Chrome, we no need to install any Add on, they provide built -in Developer Tools(F12) to inspect elements.

Element Locators are common for all Browsers.
-----------------------------------------
1) id
 

Syntax:

By.id("id value")

Examples:

driver.findElement(By.id("Email"))

driver- is Object

findElement - WebDriver method

By - pre-defined Class

id - Elment locater

Email - id locator value
-------------------------------------
driver.findElement(By.id("Email")).sendKeys("gcrindia");
--------------------------------------------
id locator for Edit box

WebElement Email = driver.findElement(By.id("Email"));
Email.sendKeys("gcrindia");
-------------------------------------------
id locator for Button

WebElement Email = driver.findElement(By.id("signIn"));
Email.click();

Or

driver.findElement(By.id("signIn")).click();
-------------------------------------------------------
2) name
 

Synatx:

By.name("name value/locator name")       

Examples:

driver.findElement(By.name("Email")).sendKeys("gcrindia");
       
Or

WebElement e = driver.findElement(By.name("Email"));
e.sendKeys("gcrindia");
------------------------------------------
WebElement e = driver.findElement(By.name("signIn"));
e.click();
------------------------------------------
3) className
 

Syntax: By.className("class name value")

Example:

driver.findElement(By.className("textboxcolor")).sendKeys("Hyderabad");
----------------------------------------------
4) tagName
 

Syntax:
By.tagName("tag name value")

Example:
driver.findElement(By.tagName("input")).sendKeys("Hyderabad");
--------------------------------------------------------------       
5) linkText
 

Syntax:
By.linkText("Link Text Value")

Example:

driver.findElement(By.linkText("Gmail")).click();
-----------------------------------------------------               
6) paritialLinkText
 

Syntax:
By.partialLinkText("Partial Link Text Value")

Example:

driver.findElement(By.partialLinkText("Gma")).click();
-----------------------------------------------
7) cssSelector
 

Syntax:
By.cssSelector("value")

Example:
driver.findElement(By.cssSelector(".gb_m")).click();
---------------------------------------------------
8) xpath
 

Syntax:

By.xpath("xpath value")

driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("abcdef");
-----------------------------------------

0 comments:

Post a Comment