
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Value to Input Web Element Using Selenium
We can set value to input webelement using Selenium webdriver. We can take the help of the sendKeys method to enter text to the input field. The value to be entered is passed as an argument to the method.
Syntax
driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");
We can also perform web operations like entering text to the edit box with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.value='<value to be entered>' and webelement as arguments to the method.
Syntax
WebElement i = driver.findElement(By.id("id")); JavascriptExecutor j = (JavascriptExecutor)driver; j.executeScript("arguments[0].value='Selenium';", i);
Example
Code Implementation
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; public class SetValue{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l=driver.findElement(By.cssSelector("input[id*='id']")); l.sendKeys("Selenium"); // obtain the value entered with getAttribute method System.out.println("Value entered is: " +l.getAttribute("value")); driver.close(); } }
Example
Code Implementation with Javascript Executor.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class SetValueJS{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement l=driver.findElement(By.cssSelector("input[id*='id']")); // Javascript Executor class with executeScript method JavascriptExecutor j = (JavascriptExecutor)driver; j.executeScript("arguments[0].value='Selenium';", l); System.out.println("Value entered is: " +l.getAttribute("value")); driver.close(); } }
Output
Advertisements