Sunday, July 15, 2018

WebElement Locators and XPath

To access web element on the page, you have to know the id, or name, or path to locate them. There are several different ways to find them. For example,

  • Browser's built-in Inspector
  • FireBug & FirePath addon in Firefox Browser
  • WebDriver Element Locator addon in Firefox Browser
  • XPath Helper in Chrome

You may find the handiest tool for yourself while using them.

There are 8 explicit locators: id, name, identifier, dom, xpath, link, css and ui, but you don't need everything while writing the test case.

Here are some examples,

id: driver.findElement(By.id("username"));
namedriver.findElement(By.name("username"));
xpathdriver.findElement(By.xpath("//*[@id='username']"));
linkdriver.findElement(By.linkText("Link Text"));
cssdriver.findElement(By.cssSelector("input[id='username']"));

What is XPath
XPath is a language that describes a way to locate and process items in Extensible Markup Language (XML) documents by using an addressing syntax based on a path through the document’s logical structure or hierarchy.

There are two types of XPath,
Absolute xpath, start from root element: /html/body/div/div/section/div/a
Relative xpath, start from located element: //*[@id=’footer’]/div/a

More examples of XPath,
//img[contains(@src,’Profile’)]
//img[starts-with(@alt,’Visit Us On Linkedin’)]
//*[text()='Simple Java Automation']
//a[contains(text(), 'Java Automation')]
//*[@id=’username’]
//input[@id=’username’]
//form[@name=’loginForm’]/input
//*[@name=’loginForm’]/input

No comments:

Post a Comment