WebDriver Element Locator Firefox Add On

 

In Selenium with Java, WebDriver Element Locators are used to find and interact with elements on a web page. For Firefox, a helpful tool to identify and inspect these elements is the Firefox Add-on called "Firebug" which is older version, or "Web Developer Tools" which is modern Firefox version. Here’s how it all fits together:


Common Element Locators in Selenium Java

  • id
  • name
  • className
  • tagName
  • linkText
  • partialLinkText
  • cssSelector
  • xpath

Modern Method: Firefox DevTools (Built-in)

No need for an external add-on anymore:

  • Right-click on any element > Inspect

  • The HTML structure opens at the bottom.

  • Right-click the element again > Copy > choose CSS Selector or XPath


How to Use in Selenium Java:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirefoxLocatorExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");

        WebDriver driver = new FirefoxDriver();
        driver.get("https://example.com");

        // Locate by ID
        WebElement elementById = driver.findElement(By.id("username"));

        // Locate by Name
        WebElement elementByName = driver.findElement(By.name("password"));

        // Locate by XPath (copied from Firefox DevTools)
        WebElement elementByXpath = driver.findElement(By.xpath("//input[@id='login']"));

        // Locate by CSS Selector
        WebElement elementByCss = driver.findElement(By.cssSelector("input[type='submit']"));

        elementByCss.click();
        
        driver.quit();
    }
}


No comments:

Post a Comment