Send Keys in selenium webdriver

sendKeys method used to pass the Keyboard keys or text into an editable elements (textbar,text area, button) without replacing the previous available content.

Using multiple sendkeys to a particular field, selenium webdriver appends all of the text one by one (example below).

Parameter(s) Accepted : sendKeys(CharSequence... keysToSend )
Return Type : void


Complete Program for Sendkeys

						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class Textbar {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// set value to textbar
								 driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
							}
						}
					

If we use Multiple sendkeys to a particular field, selenium webdriver appends them one by one to the field.


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class TextbarTwoSendkeys {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
								//send text to the same textbar and notice the change | text appended
								driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
							}
						}
					



We can clear any editable field using clear() method present in selenium webdriver, most of the time clear() will be used along with sendkeys().


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class TextbarClearSendkeys {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// set value to textbar
								 driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
								 // clear() method clears the content of a editable item
								 driver.findElement(By.xpath("//input[@id='textbar']")).clear();
								 //send text to the same textbar and notice the change
								 driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
							}
						}
					
Handle button with sendkeys

There is a misconception among most of the testers that we can use send keys only for Textbar,TextAreas, but in reality we can use sendKeys to handle a button actions like clicking operation by sending enter key from keyboard with Keys.keys


						import org.openqa.selenium.By;
						import org.openqa.selenium.Keys;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class ButtonSendkeys {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// send enter key to button
								driver.findElement(By.xpath("//input[@id='btn-sendkeys']")).sendKeys(Keys.ENTER);
							}
						}
					

Create QR Code

What is CharSequence in Sendkeys?

Have you ever noticed that Sendkeys method accepts CharSequence... arg0 parameter, but what we pass to sendkeys is a String.
sendkeys-charsequence-selenium-webdriver

CharSequence : CharSequence is an interface that represents a sequence of characters (top most class in string group ). Mutability is not enforced by this interface. Therefore, both mutable (StringBuffer, StringBuilder) and immutable (String) classes implement this interface.

As CharSequence is the top most interface, we can cast all the sub classes into this type, this is the reason behind sendkeys accepting String. When we pass a String parameter it will be automatically upcasted into CharSequence.

String - Immutable (leaves dead objects when we reassign the value)
StringBuilder and StringBuffer - Mutable (we can change the value without leaving dead object)
char-sequence-sendkeys-string


						CharSequence csString = new String("chercher.tech");
						CharSequence csStrBuffer = new StringBuffer("seleiumhq.org");
						CharSequence csStrBuilder = new StringBuilder("testng.org");
						

In above line auto-upcasting occurs, which similar to our Browser classes casting into WebDriver Interface.

String : String is a sequence of characters in Java, It is an immutable class and one of the most frequently used types in Java.

Usage of CharSequence : When we are not sure which kind of values is going to come and if we want to accept everything we would be using Object class, similarly when we want to limit the inputs only to String types (String, StringBuilder, StringBuffer) we can use CharSequence.


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;
						import org.testng.annotations.Test;

						public class CharSequenceTest {
							
							@Test
							public void test(){
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("http://google.com");
								
								// define all the strings
								CharSequence csString = new String("http://");
								CharSequence csStrBuffer = new StringBuffer("selenium-");
								CharSequence csStrBuilder = new StringBuilder("webdriver.");
								CharSequence csString2 = "com";
								
								// send the string to search bar without clearing
								driver.findElement(By.name("q")).sendKeys(csString);
								driver.findElement(By.name("q")).sendKeys(csStrBuffer);
								driver.findElement(By.name("q")).sendKeys(csStrBuilder);
								driver.findElement(By.name("q")).sendKeys(csString2);
							}
						}
						


char-sequence-sendkeys

Above program entered all the values into search box of google, without clearing the field. So we can pass StringBuilder, StringBuffer instead of string in sendkeys method of selenium webdriver

... in 'CharSequence... arg0'

What is the ... present in the Sendkeys() along with CharSequence, this symbol is known as Ellipsis aka varrags in java.

Ellipsis denotes that this method accepts Zero or more parameter of the same type, Such methods can have a variable number of arguments and thus useful for passing of dynamic data.

Using the varargs, we can avoid writing the overload methods (overload methods are nothing but same methods accepting more number of parameters or different type of parameters in same java class).

sendkeys method in selenium webdriver accepts the varargs as parameter, which means we can pass more than one string at a time, have you ever tried ?. Let's try.


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;
						import org.testng.annotations.Test;

						public class VarargsTest {
							
							@Test
							public void test(){
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("http://google.com");
								// send multiple string in send keys
								driver.findElement(By.name("q")).sendKeys("hello -", "Selenium -", "varargs");
							}
						}
						
sendkeys-varargs-webdriver-java

If you have noticed above program entered all three strings into Search box.

Below code snippet gives details about how the Varargs internally works along with sendKeys, this is my assumption and it could differ from the actual sendkeys method in selenium webdriver.


						static String asOneValue(CharSequence... args) {
							// create object for StringBuilder
							StringBuilder totalString = new StringBuilder();
							// iterate through the input values
							for(CharSequence arg : args) {
								// append the total value to the total string
								totalString.append(arg);
							}
							 // return the total string
							return totalString.toString();
						}
						

Experiment with sendkeys in selenium webdriver

This is not big experiment but probably an idea, what happens when we pass an array of strings to sendkeys ?

or
What happens when you pass elementsendkeys('string1", "string2", "string3");

Sendkeys method will add all the strings by iterating them and forms into one single string using StringBuilder and sends this value into field in selenium webdriver.


						public class StringArraySendkeys {
							@Test
							public void test(){
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("http://google.com");
								// strings
								String[] strings = {"str1", "str2", "str3"};
								driver.findElement(By.name("q")).sendKeys(strings);
							}
						}
						

Create Headless Firefox Browser in Selenium webdriver

Keys.keys with Sendkeys in Selenium Webdriver

We can stimulate the Key board using selenium webdriver with help of Keys Enum, Keys Enum also implements CharSequence.

Fields (variable or keys) Present in the Keys Enum represents pressable keys which are not text, for example : a-z are text, but Shift, Ctrl, Alt are pressabale keys but not text.

keyboard-keys-present-in-selenium-sendkeys

Below program presses 1 from the numpad and \uE01C which is nothing but unicode value of number 2 from the numpad.


						public class KeysSendkeys {
							@Test
							public void test(){
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("http://google.com");
								// press number 1 
								driver.findElement(By.name("q")).sendKeys(Keys.NUMPAD1);
								// press number 2 key
								driver.findElement(By.name("q")).sendKeys("\uE01C");
							}
						}
						
Output :
numpad-keyboard-selenium-webdriver-sendkeys

Every key represent a unicode value, Instead of Keys.value we can also pass unicode to sendkeys method in selenium webdriver. Few are given below.


  NULL         ('\uE000'),	          |	  ESCAPE       ('\uE00C'),
  CANCEL       ('\uE001'), /*^break*/|	  SPACE        ('\uE00D'),
  HELP         ('\uE002'),	          |	  PAGE_UP      ('\uE00E'),
  BACK_SPACE   ('\uE003'),	          |	  PAGE_DOWN    ('\uE00F'),
  TAB          ('\uE004'),	          |	  END          ('\uE010'),
  CLEAR        ('\uE005'),	          |	  HOME         ('\uE011'),
  RETURN       ('\uE006'),	          |	  LEFT         ('\uE012'),
  ENTER        ('\uE007'),	          |	  ARROW_LEFT   (Keys.LEFT),
  SHIFT        ('\uE008'),	          |	  UP           ('\uE013'),
  LEFT_SHIFT   (Keys.SHIFT),	      |	  ARROW_UP     (Keys.UP),
  CONTROL      ('\uE009'),	          |	  RIGHT        ('\uE014'),
  LEFT_CONTROL (Keys.CONTROL),	      |	  ARROW_RIGHT  (Keys.RIGHT),
  ALT          ('\uE00A'),	          |	  DOWN         ('\uE015'),
  LEFT_ALT     (Keys.ALT),	          |	  ARROW_DOWN   (Keys.DOWN),
  PAUSE        ('\uE00B'),	          |	  INSERT       ('\uE016'),
  SEMICOLON    ('\uE018'),	          |	  EQUALS       ('\uE019'),
		
	  // Number pad keys	
  NUMPAD0      ('\uE01A'),	          |	  NUMPAD8      ('\uE022'),
  NUMPAD1      ('\uE01B'),	          |	  NUMPAD9      ('\uE023'),
  NUMPAD2      ('\uE01C'),	          |	  MULTIPLY     ('\uE024'),
  NUMPAD3      ('\uE01D'),	          |	  ADD          ('\uE025'),
  NUMPAD4      ('\uE01E'),	          |	  SEPARATOR    ('\uE026'),
  NUMPAD5      ('\uE01F'),	          |	  SUBTRACT     ('\uE027'),
  NUMPAD6      ('\uE020'),	          |	  DECIMAL      ('\uE028'),
  NUMPAD7      ('\uE021'),	          |	  DIVIDE       ('\uE029'),
		
	  // Function keys	
  F1           ('\uE031'),	          |	  F7           ('\uE037'),
  F2           ('\uE032'),	          |	  F8           ('\uE038'),
  F3           ('\uE033'),	          |	  F9           ('\uE039'),
  F4           ('\uE034'),	          |	  F10          ('\uE03A'),
  F5           ('\uE035'),	          |	  F11          ('\uE03B'),
  F6           ('\uE036'),	          |	  F12          ('\uE03C'),
		
  META         ('\uE03D'),		  ZENKAKU_HANKAKU ('\uE040');
  COMMAND      (Keys.META),		

Multiple Keys with Keys.chord in SendKeys method

We can send multiple keys using sendkeys() in selenium webdriver, For example if we want press shift button and enter some text to a field


						import org.openqa.selenium.By;
						import org.openqa.selenium.Keys;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class SendMultipleKeys {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// enter text with capital letters by pressing Shift
								 driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys(Keys.chord(Keys.SHIFT, "UserName"));
							}
						}
					

clear() method in Selenium Webdriver

We can clear any editable field using clear() method present in selenium webdriver, most of the time clear() will be used along with sendkeys().


              import org.openqa.selenium.By;
              import org.openqa.selenium.WebDriver;
              import org.openqa.selenium.chrome.ChromeDriver;
  
              public class TextbarClearSendkeys {
                public static void main(String[] args) {
                  // set chrome driver exe path
                  System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
                  WebDriver driver = new ChromeDriver();
                  driver.get("https://chercher.tech/selenium-webdriver-sample");
                  // set value to textbar
                   driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
                   // clear() method clears the content of a editable item
                   driver.findElement(By.xpath("//input[@id='textbar']")).clear();
                   //send text to the same textbar and notice the change
                   driver.findElement(By.xpath("//input[@id='textbar']")).sendKeys("selenium webdriver");
                }
              }
            

Add Screenshots to the PDF file in selenium

click() method in selenium webdriver

Webpage testing happens with clicks most of the time, selenium provides a method called click() which helps the user to click on the elements on webpage.

To click any element on webpage selenium must find the element first, and element should have width and height more than '0px'.

Element must be visible on the webpage.


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class Link {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// clicks the link which has id = 'button'
								driver.findElement(By.xpath("//a[@id='link']")).click();
							}
						}
					


To click a button


						import org.openqa.selenium.By;
						import org.openqa.selenium.WebDriver;
						import org.openqa.selenium.chrome.ChromeDriver;

						public class Button {
							public static void main(String[] args) {
								// set chrome driver exe path
								System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
								WebDriver driver = new ChromeDriver();
								driver.get("https://chercher.tech/selenium-webdriver-sample");
								// clicks the button which has id = 'button'
								driver.findElement(By.id("button")).click();
							}
						}

					


We can use click() method to click the checkbox and uncheck checkbox


					import org.openqa.selenium.By;
					import org.openqa.selenium.WebDriver;
					import org.openqa.selenium.chrome.ChromeDriver;

					public class Checkbox {
						public static void main(String[] args) {
							// set chrome driver exe path
							System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
							WebDriver driver = new ChromeDriver();
							driver.get("https://chercher.tech/selenium-webdriver-sample");
							// clicks the check which has id = 'checkbox'
							driver.findElement(By.id("checkbox")).click();
						}
					}
					


We can use click() method to click the radio button, as we know we cannot un-select a radio button by clicking it. To un-select a radio button we need to click another radio button.


					import org.openqa.selenium.By;
					import org.openqa.selenium.WebDriver;
					import org.openqa.selenium.chrome.ChromeDriver;

					public class Radio {
						public static void main(String[] args) {
							// set chrome driver exe path
							System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
							WebDriver driver = new ChromeDriver();
							driver.get("https://chercher.tech/selenium-webdriver-sample");
							// clicks the radio button which has id = 'radio'
							driver.findElement(By.id("radio")).click();
						}
					}
					

Type Casting in Method Overloading in Java Selenium

How to write a custom click method in selenium webdriver?

Sometimes we may need to write our own methods to click, so that before click or after click we can perform some operations, also we will have the clicking operation happening in one place.

In case if there is a change in click() method of selenium webdriver, we can easily modify or update the method in one place instead of multple places.


                        	import org.openqa.selenium.By;
							import org.openqa.selenium.WebDriver;
							import org.openqa.selenium.WebElement;
							import org.openqa.selenium.firefox.FirefoxDriver;

							public class CustomClick {
								// open firefox and store it in driver and driver is static here (driver not webdriver)
								public static WebDriver driver = new FirefoxDriver();
								public static void main(String[] args) {
									driver.get("https://chercher.tech/java/explicit-wait-sample");
									WebElement button = driver.findElement(By.xpath("//button[@id='disable']"));
									customClick(button);
								}
								public static void customClick(WebElement element){
									System.out.println("you can write the custom loogin/ or print statements");
									element.click();
									System.out.println("you can write the custom loogin/ or print statements");
								}
							}
						

Reasons for click() method to fail in selenium webdriver

1. There no such element
2. Element is not visible
3. Element Not clickable
4. Element Height and width is less than 0 (zero)
5. Check the xpath case(upper and lower) few it depends on the browser

Submit

submit() method in selenium webdriver submits a form, user can use it only along with form or with form element only.

submit() method clicks a button is a misconception, it works only when that particular button is associated with form.

@parameters : accepts nothing
@return : nothing

submit form in selenium webdriver


										import org.openqa.selenium.By;
										import org.openqa.selenium.WebDriver;
										import org.openqa.selenium.chrome.ChromeDriver;

										public class Submit {
											public static void main(String[] args) {
												// set chrome driver exe path
												System.setProperty("webdriver.chrome.driver", "C:/~/chromedriver.exe");
												WebDriver driver = new ChromeDriver();
												driver.get("https://chercher.tech/selenium-webdriver-sample");
												// submits the button which has type as submit
												driver.findElement(By.id("//button[@type='submit']")).submit();
											}
										}
							

Ways to select dropdown option in selenium

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Reply
  • Copyright © CherCher Tech