Selenium: how to add data to a text box or text

I am using the Selenium Web driver. I have a text area where some text is written. Now How can I add some text / html in it or paste data in a specific place?

The following code adds it to a text area / text field

driver.findElement(By.xpath("textBox/textArea")).sendKeys("abc"); 

i.e. if the text area / text field contains 123. The result above will be 123abc . But I want abc123 or 12abc3

PS: I am testing the functionality of "Email Reply". So, as a user, when you reply to mail, you do not copy the text, and then clear all the text, and then copy all the text after writing new text, as shown below:

 WebElement element = driver.findElement(By.xpath("textBox/textarea")); String previousText = element.getAttribute("value"); element.clear(); element.sendKeys("abc" + previousText); 

Please, help...

+4
source share
3 answers
 import org.openqa.selenium.Keys; ... WebElement element = driver.findElement(By.xpath("textBox/textarea")); element.sendKeys(Keys.HOME + "abc"); 

or maybe for multi-line text areas

 element.sendKeys(Keys.CONTROL, Keys.HOME); element.sendKeys("abc"); 
+7
source
  WebElement element = driver.findElement(By.xpath("textBox/textarea")); String previousText = element.getAttribute("value"); element.clear(); element.sendKeys("abc" + previousText); 
+2
source

You can insert text using a robot.
Following my path.
I hope this helps you.

 public void runScript() { WebElement textarea = driver.findElement(By.id("textarea")); insert(textarea, "abc", 2); } public void insert(WebElement textElement, String insertText, int offset) { String currentText = textElement.getText(); int len = currentText.length(); if (len < offset) { throw new IllegalArgumentException(String.format("len(%d) < offset(%d)", len, offset)); } Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } robot.setAutoDelay(20); // On focus. textElement.click(); // Move cursor for head. type(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_HOME); for (int i = 0; i < offset; i++) { type(robot, KeyEvent.VK_RIGHT); } textElement.sendKeys(insertText); } public void type(Robot robot, int... keycodes) { for (int keycode : keycodes) { robot.keyPress(keycode); } for (int keycode : keycodes) { robot.keyRelease(keycode); } } 
0
source

Source: https://habr.com/ru/post/1446394/


All Articles