Click on link

By xngo on February 22, 2019

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

/**
 * Selenium v2: Click on a simple link(e.g Next)
 * 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 ClickExample
{
  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/clickLinkTest.html");
 
    // Find and click on the Next link.
    WebElement oClickElem = oWebDriver.findElement(By.linkText("Next")); // Find Next link.
    oClickElem.click(); // Click on the element found(i.e. Next).
 
    // Pause so that you can see that Selenium has clicked.
    pause(5000);
 
    // 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.