Pressing Ctrl + A in Selenium WebDriver

Viewed 224785

Is there a way to press the Ctrl + A keys using Selenium WebDriver?

I checked the Selenium libraries and found that Selenium allows key press of special and function keys only.

15 Answers

For Python:

ActionChains(driver).key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform();

The simplest answer in C# (if you are C# inclined).

Actions action = new Actions(); 
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();

This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.

I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.

Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.

Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

This is what worked for me using C# (Visual Studio 2015) with Selenium:

new Actions(driver).SendKeys(Keys.Control + "A").Perform();

You can add as many keys as wanted using (+) in between.

Java

The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:

Example:

Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);

To use the above Robot class, you need to import java.awt.Robot;'.

Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).build().perform();

Below code worked for me.

WebElement textbox = driver.findElement(By.id("username"));
textbox.sendKeys("Testing");
textbox.sendKeys(Keys.CONTROL+"A");
Related