Click on any html element using different locators

By xngo on February 22, 2019

For similar example using Selenium v1, see [node:54].

/**
 * Selenium v2: Click on any html element in the webpage as long as you can use the locators to identify them.
 * Assume that you have Internet Explorer.
 * @Author: Xuan Ngo
 */
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
public class ClickAnyElementExample
{
  public static void main(String[] args)
  {
    // All actions will be applied to Internet Explorer
    WebDriver oWebDriver = new InternetExplorerDriver();
 
    // Open the webpage.
    oWebDriver.get("https://openwritings.net/sites/default/files/selenium-test-pages/ClickAnyElementExample.html");
 
    WebElement oClickElem = null;
 
    // Using name locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.name("submit_button")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(1000); // Pause so that you can see that Selenium had clicked.
 
    // Using ID locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.id("unique-link-id")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(1000); // Pause so that you can see that Selenium had clicked.
 
    // Using XPATH locator: Find and click on the Next link.
    oClickElem = oWebDriver.findElement(By.xpath("//li[contains(text(), 'using the xpath')]")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
    pause(3000); // Pause so that you can see that Selenium had clicked.
 
    // Close the browser.
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.