How to specify "ENTER" button functionality in Selenium WebDriver code?

SeleniumAutomation TestingTesting Tools

To specify ENTER button functionality in Selenium webdriver we have to use the method sendKeys. To simulate pressing the ENTER button,we have to add the statement import org.openqa.selenium.Keys to our code.

Then pass the parameter – Keys.RETURN or Keys.ENTER to the sendKeys method.

Let us make an attempt to press the ENTER button after entering some text in the Google search input box −

Example

Code Implementation with Keys.ENTER

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class EnterOperation{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.manage().window().maximize();
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement e =driver.findElement(By.name("q"));
      e.sendKeys("Java");
      // Keys.ENTER with sendKeys
      e.sendKeys(Keys.ENTER);
   }
}

Code Implementation with Keys.RETURN

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class EnterOperationReturn{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.manage().window().maximize();
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement r =driver.findElement(By.name("q"));
      r.sendKeys("Java");
      // Keys.RETURN with sendKeys
      r.sendKeys(Keys.RETURN);
   }
}

Output

raja
Published on 03-Apr-2021 10:24:51
Advertisements