Sendkeys in selenium Webdriver

SendKeys for entering text in textbox

sendkeys is widely used function in Selenium. it is used to send the text into the text box. so it is a inbuilt function the Selenium.

You can see in the below code we are sending text into the text box which are identified by using xpath it is very simple and convenient way to send a text into the textbox

driver.findElement(By.xpath("//label[text()='User Name:']/following::div/input")).sendKeys("UserName");
driver.findElement(By.xpath("//label[text()='Password:']/following::div/input")).sendKeys("Password");

We can also pass variable to the sendkeys you can see in the below example

public void searchFor(String query) {
driver.findElement(By.cssSelector("input[name='q']")).sendKeys(query);
driver.findElement(By.cssSelector("input[type='submit']")).click();
}

Sendskeys to Focus an Element

sendkeys  in selenium is also used to focus an element on the web page. because sometimes when we try to directly enter the text into the textbox itself or if you want to click on the element but WebDriver is not able to focus on the element so in that case we use sendkeys so that element will get focus and after that we can perform different actions on that element

so to focus on an element on the web page in Selenium we use below code of sendkeys is we pass nothing into the sendkeys and by using this trick we can focus an element into the webpage

element.sendKeys("");

Sendkeys for Uploading files

Sendkeys in the Selenium has various different types of uses you can also use sendkeys for uploading a document on a webpage yes you have read it right you can also upload an document using the sendkeys so yes sendkey in Selenium is a magical word.

You can upload different types of files using sendkeys like Doc, Excel, PDF , image etc

WebElement element = = driver.findElement(By.name("file")) ;
element.sendKeys("D:/file.txt");

Show file in the above example is a name attribute of the upload button.  In sendkeys we have passed the path of the folder in which is located into our local machine

sendkeys in selenium for Key Press

We cannot use sendkeys in selenium for keyboard events as you can see in the below screenshot I have used sendkeys for pressing enter key of the keyboard and is very simple to use you just have to define keys in the sendkeys method and the respective key you want to press on the keyboard

sendkeys selenium

So as we have seen there are different types of uses of sendkeys in Selenium which we can incorporate into our scripts. You  main also like to  read an Selenium interview questions  for your upcoming interview

If you know any other use of sendkeys  in selenium please let me know in the comment section below…

Author: Saad Mansuri

Leave a Reply

Your e-mail address will not be published. Required fields are marked *