Key press in (Ctrl+A) Selenium WebDriver.


We can perform key press of (CTRL+A) with Selenium Webdriver. There are multiple ways to do this. We can use the Keys.chord() method to simulate this keyboard action.

The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method. To press CTRL+A, it takes, Keys.CONTROL, "a" as parameters.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class PressCtrlA{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // enter text then ctrl+a with Keys.chord()
      l.sendKeys("Selenium");
      String s = Keys.chord(Keys.CONTROL, "a");
      l.sendKeys(s);
      driver.quit()
   }
}

We can also perform a CTRL+A press by simply using the sendKeys() method. We have to pass Keys.CONTROL along with the string A by concatenating with +, as an argument to the method.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class SendCtrlA{
   public static void main(String[] args) {     System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // enter text then ctrl+a
      l.sendKeys("Selenium");
      l.sendKeys(Keys.CONTROL+"A");
      driver.quit()
   }
}

Output

Updated on: 18-Sep-2020

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements