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();
    }
}


How to use Robot Class in Selenium

  

The Robot Class in Java belongs to the java.awt package. It is used in Selenium to handle keyboard and mouse events that cannot be handled using the WebDriver or Actions class such as file upload windows, OS-level popups, or simulating keyboard shortcuts like Ctrl+S, Alt+Tab, etc.


Use Cases of Robot Class

  • Handling file upload dialogs (OS windows)

  • Simulating keyboard shortcuts (example: Ctrl+C, Enter)

  • Performing mouse movements or clicks outside the browser

  • Dealing with download popups, print popups, etc.


Common Robot Class Methods

MethodDescription
keyPress(int keycode)Presses a key
keyRelease(int keycode)Releases a key
mouseMove(int x, int y)Moves mouse pointer to (x, y) screen coordinates
mousePress(int buttons)Presses mouse buttons
mouseRelease(int buttons)Releases mouse buttons
delay(int ms)Delays execution for specified milliseconds


Uses KeyEvent.VK_* constants for keys, e.g., KeyEvent.VK_ENTER, KeyEvent.VK_CONTROL.


File upload example: Selenium Script Using Robot Class 

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class RobotClassFileUploadExample {
    public static void main(String[] args) throws AWTException, InterruptedException {
        // Set path to chromedriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize driver
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        // Open sample file upload site
        driver.get("https://www.filemail.com/share/upload-file");

        // Click on "Add Files" button to open OS file upload dialog
        driver.findElement(By.xpath("//button[text()='Add Files']")).click();

        // Wait for file upload window to appear
        Thread.sleep(2000);

        // Set the file path to clipboard
        StringSelection filePath = new StringSelection("C:\\Users\\YourUser\\Documents\\sample.txt");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePath, null);

        // Use Robot to press CTRL+V and Enter
        Robot robot = new Robot();
        robot.delay(1000);

        // Press CTRL + V
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

        robot.delay(500);

        // Press Enter
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

        // Done!
        Thread.sleep(3000);
        driver.quit();
    }
}


Suppose we are uploading a file to a form, and we need to handle the OS file chooser window:



Explanation:

  • StringSelection + Toolkit.getDefaultToolkit().getSystemClipboard() → Puts file path into clipboard.

  • Robot simulates Ctrl+V and Enter to paste the path and upload the file.


Important points:

  • Robot class interacts outside of browser context, so it can handle system-level dialogs.

  • Always add Thread.sleep() or robot.delay() to ensure the timing is synced properly with the UI events.

Right Click and Double Click in Selenium

 

In Selenium with Java, you can perform Right Click (Context Click) and Double Click using the Actions class from the org.openqa.selenium.interactions package.


1. Right Click (Context Click) Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class RightClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html");

        // Find the element to right click
        WebElement element = driver.findElement(By.cssSelector(".context-menu-one"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Right Click (Context Click)
        actions.contextClick(element).perform();

        // Optional: Click on a menu item if needed
        WebElement menuItem = driver.findElement(By.cssSelector(".context-menu-item.icon-copy"));
        menuItem.click();

        driver.quit();
    }
}


font-size:14px;

2. Double Click Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DoubleClickExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/simple_context_menu.html");

        // Find the button to double-click
        WebElement button = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));

        // Create Actions class object
        Actions actions = new Actions(driver);

        // Perform Double Click
        actions.doubleClick(button).perform();

        // Handle the alert
        driver.switchTo().alert().accept();

        driver.quit();
    }
}


Important Points:

  • You must call .perform() at the end to actually execute the action.

  • Make sure to import Actions class:

import org.openqa.selenium.interactions.Actions;

Actions Class in Selenium

 

In Selenium WebDriver (Java), the Actions class is used to handle complex user interactions and advanced gestures like mouse movements, key presses, drag-and-drop, right-clicks, double-clicks, etc.


Why Use Actions Class?

  • Simulate mouse and keyboard actions

  • Handle advanced interactions not possible with simple WebElement methods


Import Statement:

import org.openqa.selenium.interactions.Actions;


Creating an Actions Object:

Actions actions = new Actions(driver);
Where driver is your instance of WebDriver.


Common Methods of Actions Class:

MethodDescription
click()Clicks at the current mouse location
click(WebElement)Clicks on a given element
doubleClick() / doubleClick(element)Double-clicks
contextClick() / contextClick(element)Right-clicks
moveToElement(element)Moves mouse to element
dragAndDrop(source, target)Drags source to target
clickAndHold() / release()Click and hold / release
sendKeys(Keys.XXX)Sends keyboard keys


Most of these methods are chained and must be followed by .perform() to execute.


Example Code Snippets:

1. Mouse Hover

WebElement element = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(element).perform();

2. Right Click (Context Click)

WebElement element = driver.findElement(By.id("rightClickBtn"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

3. Double Click

WebElement element = driver.findElement(By.id("doubleClickBtn"));
Actions actions = new Actions(driver);
actions.doubleClick(element).perform();

4. Drag and Drop

WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();

5. Click and Hold / Release

Actions actions = new Actions(driver);
actions.clickAndHold(source).moveToElement(target).release().perform();


6. Keyboard Events Example:

actions.sendKeys(Keys.ENTER).perform();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();


Browser Commands in Selenium

  

Browser commands in Selenium WebDriver allow you to interact with the browser as a whole, such as opening, closing, navigating, and retrieving information. Here are the most common browser commands:


List of Browser Commands:

CommandDescription
driver.get("URL")Opens a website
driver.getCurrentUrl()Returns the current URL
driver.getTitle()Returns the title of the page
driver.getPageSource()Returns the page source
driver.close()Closes the current browser window
driver.quit()Closes all browser windows and ends the session
driver.navigate().to("URL")Navigates to a specific URL
driver.navigate().back()Goes back to the previous page
driver.navigate().forward()Goes forward to the next page
driver.navigate().refresh()Refreshes the current page


Selenium Java code using browser commands

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserCommandsDemo {
    public static void main(String[] args) {

        // Set path to chromedriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();

        // 1. Open a website
        driver.get("https://www.google.com");

        // 2. Get current URL
        String currentUrl = driver.getCurrentUrl();
        System.out.println("Current URL: " + currentUrl);

        // 3. Get page title
        String title = driver.getTitle();
        System.out.println("Page Title: " + title);

        // 4. Navigate to another URL
        driver.navigate().to("https://www.bing.com");

        // 5. Navigate back
        driver.navigate().back();

        // 6. Navigate forward
        driver.navigate().forward();

        // 7. Refresh the page
        driver.navigate().refresh();

        // 8. Get page source
        String pageSource = driver.getPageSource();
        System.out.println("Page Source Length: " + pageSource.length());

        // 9. Close the current window
        driver.close();

        // Optional: Quit the entire browser session
        // driver.quit();
    }
}

Integration of Appium with Cucumber and Testng for IOS App

 


Below is the code which is showing integration of Appium with Cucumber and Testng for IOS app. Please have a look.



Maven Dependencies:

<dependencies>
    <!-- Cucumber -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.16.1</version>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>7.16.1</version>
    </dependency>

    <!-- Appium -->
    <dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>9.0.0</version>
    </dependency>

    <!-- TestNG -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.9.0</version>
        <scope>test</scope>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.7</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <!-- Compiler plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.11.0</version>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>

        <!-- Surefire plugin for TestNG -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.2.5</version>
            <configuration>
                <includes>
                    <include>**/TestRunner.java</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>






Feature File (src/test/resources/features/login.feature)


Feature: Login Feature

  Scenario: Verify login with valid credentials
    Given I launch the iOS app
    When I enter valid credentials
    Then I should see the home screen





Step Definitions (stepdefinitions/LoginSteps.java)


package stepdefinitions;

import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.remote.IOSMobileCapabilityType;
import io.cucumber.java.en.*;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.net.URL;

public class LoginSteps {

    public static IOSDriver driver;

    @Given("I launch the iOS app")
    public void launchApp() throws Exception {
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("platformName", "iOS");
        caps.setCapability("platformVersion", "16.4");
        caps.setCapability("deviceName", "iPhone 14");
        caps.setCapability("automationName", "XCUITest");
        caps.setCapability("app", "/path/to/your.app");

        driver = new IOSDriver(new URL("http://127.0.0.1:4723/wd/hub"), caps);
    }

    @When("I enter valid credentials")
    public void enterCredentials() {
        // Locate and interact with username and password fields
        // driver.findElement(By.id("username")).sendKeys("testuser");
        // driver.findElement(By.id("password")).sendKeys("password");
        // driver.findElement(By.id("loginButton")).click();
    }

    @Then("I should see the home screen")
    public void verifyHomeScreen() {
        // Assert that home screen element is displayed
        // Assert.assertTrue(driver.findElement(By.id("home")).isDisplayed());
        driver.quit();
    }
}






Cucumber TestNG Runner (runner/TestRunner.java)


package runner;

import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;

@CucumberOptions(
    features = "src/test/resources/features",
    glue = "stepdefinitions",
    plugin = {"pretty", "html:target/cucumber-reports.html"},
    monochrome = true
)
public class TestRunner extends AbstractTestNGCucumberTests {
}






Run Tests

mvn clean test





Testng.xml:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="iOS Test Suite">
  <test name="Cucumber Tests">
    <classes>
      <class name="runner.TestRunner" />
    </classes>
  </test>
</suite>





Important Points:

  • Start Appium server before running.

  • WebDriverAgent must be built on your device once via Xcode.

  • Provide correct .app or .ipa path in DesiredCapabilities.

Geckodriver in Selenium

  

Here's a simple Selenium test script in Java using GeckoDriver (for Firefox) to:

  • Open Firefox browser

  • Navigate to Google

  • Search for "Selenium WebDriver"

  • Print the page title


Prerequisites for executing selenium script on firefox browser:

  • JDK installed
  • Firefox installed
  • GeckoDriver downloaded and path set to system or specified in code
  • Selenium Java JARs added to project (e.g., via Maven or manually)


Selenium Java Script using GeckoDriver

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

public class GoogleSearchTest {
    public static void main(String[] args) {
        // Set path to geckodriver (change path accordingly)
        System.setProperty("webdriver.gecko.driver", "C:\\path\\to\\geckodriver.exe");

        // Initialize Firefox driver
        WebDriver driver = new FirefoxDriver();

        // Open Google
        driver.get("https://www.google.com");

        // Locate search box, type query, and submit
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("Selenium WebDriver");
        searchBox.submit();

        // Wait for page to load (can also use WebDriverWait for better practice)
        try {
            Thread.sleep(3000); // simple sleep for demo (not recommended in real tests)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print page title
        System.out.println("Page title is: " + driver.getTitle());

        // Close browser
        driver.quit();
    }
}


if we are using maven, add this dependency:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.19.1</version> <!-- Check latest -->
</dependency>