2.2 Day12-Locators PDF
2.2 Day12-Locators PDF
Agenda
➢ Locators in WebDriver
Locators
• We can identify various elements on the web using Locators.
• Locators are addresses that identify a web element uniquely within the page.
Locators
Linktext
id name CSS Selector XPath
PartialLinktext
driver.findElement(By.cssSelector("input.inputtext")).sendkeys("[email protected]");
CSS Selector – Tag and Attribute
driver.findElement(By.cssSelector("input[name=lastName]")).sendkeys("xxxxx");
CSS Selector - Tag, class and attribute
driver.findElement (By.cssSelector("input.inputtext[tabindex=2]").sendkeys("xxxx");
XPath
• XPath is for locating the elements or nodes in XML documents
• Hence XPath can be used to locate elements in HTML pages (web pages).
Capture XPath
Types of XPath
➢There are two types of XPath:
1. Absolute XPath .
2. Relative XPath .
Absolute XPath
➢ It
is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes
made in the path of the element then that XPath gets failed.
Examples:
// a [@href=’http://www.google.com’]
//input[@id=’name’]
//input[@name=’username’]
//img[@alt=’sometext’]
XPath with Multiple attributes
//tagname[@attribute1=’value1’][attribute2=’value2’]
Examples:
//a[@id=’id1’][@name=’namevalue1’]
//img[@src=’’][@href=’’]
XPath with text() method
• Xpath=//td[text()='UserID']
XPath with Contains() method
//tagname[contains(@attribute,’value1’)]
//input[contains(@id,’’)]
//input[contains(@name,’’)]
//a[contains(@href,’’)]
//img[contains(@src,’’)]
//div[contains(@id,’’)]
XPath with starts-with() method
//tagname[starts-with(@attribute-name,’’)]
Examples:
//id[starts-with(@id,’’)]
//a[starts-with(@href=’’)]
//img[starts-with(@src=’’)]
//div[starts-with(@id=’’)]
//input[starts-with(@id=’’)]
//button[starts-with(@id,’’)]
Using OR, AND with XPath
//*[@type='submit' OR @name='btnReset’] //input[@type='submit' and @name='btnLogin']
Following
➢ Selects all elements in the document of the current node
//*[@type='text']//following::input[1]
//*[@type='text']//following::input
Preceding
➢ Select all nodes that come before the current node
//*[@type='submit']//preceding::input
Summary of Locators
Locators Description Example
By.className finds elements based on the value of the "class" attribute findElement(By.className("someClassName"))
By.partialLinkText locates elements that contain the given link text findElement(By.partialLinkText("REG"))