Home > Blockchain >  How to efficiently send large String to java selenium textarea element
How to efficiently send large String to java selenium textarea element

Time:09-21

I need to send Large text in the type of String to textArea element. I use

driver.findElement(By.xpath(textarea_xpath)).sendKeys(fileText);

But Its too slow. Any ideas to make this fast?

CodePudding user response:

You can try it with JS executor:

  public void enterTextJS(By locator, String text) {
    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
    WebElement element = driver.findElement(locator);
    jsExecutor.executeScript("arguments[0].value='"   text   "';", element);
  }

CodePudding user response:

Basicaly same solution as Villa_7's. Setting text of 6k chars takes ~ 25 miliseconds.

package selenium;

import java.time.LocalDateTime;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class OmarHafez extends WebDriverSetup {

    public static void main(String[] args) {

        WebDriver driver = startChromeDriver();
        driver.get("https://demoqa.com/automation-practice-form");
        WebElement addressField = driver.findElement(By.tagName("textarea"));
        addressField.click();
        String s = randomStringOfLength(6000);
        System.out.println(LocalDateTime.now());
        String js = "document.evaluate(\"//textarea[@id='currentAddress']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = '"   s   "';";
        JavascriptExecutor javascriptExecutor = (JavascriptExecutor)driver;
        javascriptExecutor.executeScript(js);
        System.out.println(LocalDateTime.now());
        System.out.println(addressField.getAttribute("value"));
        driver.quit();
    }
    
    public static String randomStringOfLength(int length) {
        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        Random random = new Random();
        String generatedString = random.ints(leftLimit, rightLimit   1)
          .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
          .limit(length)
          .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
          .toString();
        return generatedString;
    }

}
  • Related