Single Post

Header

Sunday, November 1, 2015

Selenium WebDriver Examples for different locator methods of "By" class

Example for how to locate Selenium WebDriver methods of By class 
Explained with examples of all the methods of Selenium web driver By class

1.By.id 
2.By.name
3.By.className
4.By.linkText
5.By.partialLinkText
6.By.cssSelector
7.By.xpath
8. By.tagName

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumDifferentLocators {

@Test
public void seleniumByMethods() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
// Open website
driver.get("http://docs.seleniumhq.org/");
// Maximize web browser
driver.manage().window().maximize();

// Use By.name Webdriver
// Send "selenium" text at search selenium textbox.
// <input id="q" type="text" size="30" accesskey="s" name="q">
driver.findElement(By.name("q")).sendKeys("selenium");

// Use By.id Webdriver
// Click on "Go" button besides at search selenium textbox.
// <input id="submit" type="submit" value="Go">
driver.findElement(By.id("submit")).click();
Thread.sleep(3000);
// Navigate browser to back
driver.navigate().back();
Thread.sleep(3000);

// Use By.className Webdriver
// Click on "Download Selenium"
// <div class="downloadBox">
   driver.findElement(By.className("downloadBox")).click();

// Use By.linkText Webdriver
// Click on "Documentation" tab
 // <a title="Technical references and guides" href="/docs/">Documentation</a>
driver.findElement(By.linkText("Documentation")).click();
Thread.sleep(3000);

// Use By.partialLinkText Webdriver. Giving partial text of the link.
/* <a class="reference internal" href="01_introducing_selenium.jsp#test-automation-for-web-applications"> Test Automation for Web Applications</a> */
driver.findElement(By.partialLinkText("Test")).click();
driver.navigate().back();
Thread.sleep(3000);

// Use By.cssSelector Webdriver
// Click on "Download Selenium"
// <a class="reference internal" href="00_Note_to-the-reader.jsp">
   driver.findElements(By.cssSelector(".reference.internal")).get(0).click();
driver.navigate().back();
Thread.sleep(3000);

// Use By.xpath Webdriver
// Click on "About" tab
// <li id="menu_about"> <a title="Overview of Selenium" href="/about/">About</a> </li>
driver.findElement(By.xpath(".//*[@id='menu_about']/a")).click();

  // Use By.tagName Webdriver
  // Get "Browser Automation" text
  // <a title="Return to Selenium home page" href="/">Browser Automation</a>
  String linkName = driver.findElement(By.tagName("a")).getText();
  System.out.println(linkName);

// Close the browser
driver.close();
}


}

No comments:

Post a Comment