19.1.1. Locators
19.1.1. Locators
Locators :
1. Locators are used to identify an element present in a webpage with the help of
locator types.
2. To identify an element present in a webpage we need to use findElement()
method which is present in WebDriver interface.
3. findElement() method will identify an element with the help of “By” class which
contains static methods.
4. All the static methods present in a By class are known as locator types.
Xpath :
WebDriver driver = new ChromeDriver();
driver.get(“url”);
driver.findElement(By.xpath(“xpath_expression”)).sendkeys(“abc”);
Types of xpath :
1. xpath by attribute
Syntax :
//tagname[@attribute name = ‘attribute value’]
e.g. :- //input[@id = ‘abc’], //input[@id='autocomplete']
driver.findElement(By.xpath(“//input[@id = ‘abc’]”).click();
2. xpath by text
Syntax :
//tagname[text() = ‘textvalue’]
e.g. :- //a[text() = ‘link1’]
3. xpath by contains()
a. Here we can mention the substring without writing a whole text, when
link/text is big in size.
b. If any non-breakable space (nbsp) is there.
We can use contains in two ways :
I. Contains with text() :
//tagname[contains(text(),’textvalue’)]
//h2[text()='Facebook helps you connect and share with the people in
your life.']→ normal text method
//h2[contains(text(),'Facebook ')]→using contains text
//a[contains(text(),‘link1’)]
II. Contains with attribute :
//tagname[contains(@attribute name, ‘attribute value’)]
//input[contains(@name,‘first’)], //img[contains(@alt,'gle')]
4. xpath by index
(//tagname[@attribute name = ‘attribute value’] )[2]
(//input[@type = ‘text’] )[2]
(//input[@name='radio'])[2]
(//h1[contains(text(),'Practice Page')])[1]
/html/body/div[2]/input[1]-→//div[2]/input[1]
HTML Tree Diagram
html
body
div[1]
input[1] – URL
input[2] – PWD
div[2]
input[1] – male
input[2] – female
div[3]
a[1] – link1
a[2] – link2
input – submit
<html>
<body>
<div>
UN<input type = ‘text’>
PWD<input type = ‘password’>
</div>
<div>
male<input type = ‘radio’>
female<input type = ‘radio’>
</div>
<div>
<a href = ‘_’> link1
<a href = ‘_’> link2
<button type = ‘submit’ value = ‘login’>
</div>
</body>
</html>
Absolute Relative
/html/body/div[3]/a[1] //div[3]//a[1]
/html/body/div[3]/input //div[3]//input or input[5]
/html/body/div[2]/input[2] //div[2]//a[2] or input[4]