Java 如何在 selenium webdriver 的文本字段中一个一个地输入字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24492795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:35:01  来源:igfitidea点击:

How to enter characters one by one in to a text field in selenium webdriver?

javaseleniumselenium-webdriver

提问by Rajendra Narayan Mahapatra

How to enter characters one by one in to a text field in selenium webdriver? I have used the below code but it's not working

如何在 selenium webdriver 的文本字段中一个一个地输入字符?我使用了下面的代码,但它不起作用

getDriver().findElement(By.id("PhoneNumber")).sendKeys(Keys.chord("9876544322"));

Can anybody suggest how to resolve this?

有人可以建议如何解决这个问题吗?

回答by tim-slifer

.chord() will press all keys simultaneously. Not very well suited for field input.

.chord() 将同时按下所有键。不太适合现场输入。

The .sendKeys() method will accept a String. Simply pass your input as such and have a go with it.

.sendKeys() 方法将接受一个字符串。简单地传递您的输入并尝试一下。

driver.findElement(By.id("element")).sendKeys("Field Input Text");

回答by tim-slifer

sendKeys()does enter characters in sequence, but it can at times run quickly enough to be perceived as a copy/paste action. Though, it is in fact intended to simulate a user entering text by typing. Per the sendKeys()JavaDoc:

sendKeys()确实按顺序输入字符,但它有时可以运行得足够快以被视为复制/粘贴操作。尽管如此,它实际上是为了模拟用户通过打字输入文本。根据sendKeys()JavaDoc:

/** Use this method to simulate typing into an element, which may set its value. */

/** 使用这个方法来模拟输入一个元素,它可以设置它的值。*/

If you wanted to slow it down, you could make a method that accepts WebElement and String args, convert the String to charsequence[], then use a for loop and enter each index of the array in the .sendKeys() followed by a Thread.sleep(). This seems horribly inefficient, though, as sendKeys()recognizes Strings as charsequence[](String isa charsequence[]in Java). Adding the Thread.sleep()will only slow your test needlessly.

如果您想减慢速度,您可以创建一个接受 WebElement 和 String args 的方法,将 String 转换为charsequence[],然后使用 for 循环并在 .sendKeys() 中输入数组的每个索引,后跟一个Thread.sleep()。这似乎很没效率的,但是,作为sendKeys()识别字符串作为charsequence[](字符串一个charsequence[]在Java中)。添加Thread.sleep()只会不必要地减慢您的测试速度。

Honestly, sendKeys()fits your described needs. It's the best way to simulate a user at a keyboard, it just does it really fast.

老实说,sendKeys()符合您描述的需求。这是在键盘上模拟用户的最佳方式,它的速度非常快。

回答by Mar?i? Paul

Here is how I am sending character by character using Selenium Webdriver (in Java). This way in the back-end, I verify at each letter press if the character exists in the input. Normal element.sendKeys()is not working well for me 2 out of 5 times - the last letter is missing, I guess something is buggy with Selenium Webdriver, I don't know. Try the code below, it works 100% of the time for me.

这是我如何使用 Selenium Webdriver(在 Java 中)逐个字符发送。这样在后端,我会在每次按下字母时验证输入中是否存在该字符。Normalelement.sendKeys()对我来说 5 次中有 2 次效果不佳 - 最后一个字母丢失了,我想 Selenium Webdriver 有问题,我不知道。试试下面的代码,它对我来说 100% 的时间都有效。

public void TypeInField(String xpath, String value){
    String val = value; 
    WebElement element = driver.findElement(By.xpath(xpath));
    element.clear();

    for (int i = 0; i < val.length(); i++){
        char c = val.charAt(i);
        String s = new StringBuilder().append(c).toString();
        element.sendKeys(s);
    }       
}

As you see, I get the value needed to be typed and in the forloop, I take each character, convert it to string and send it to textbox. Also, I have a search for xpath, you can change that to id, or classname, or whatever you want.

如您所见,我获得了需要输入的值,并在for循环中获取每个字符,将其转换为字符串并将其发送到文本框。另外,我搜索了 xpath,您可以将其更改为 id、类名或任何您想要的。

回答by user10330446

I use this function in my test when I want to type a string letter by letter.

当我想一个字母一个字母地输入一个字符串时,我在我的测试中使用这个函数。

public void typeOnLetterByLetter(WebElement webElement, String value, long waitBetweenLetters, ChronoUnit unitTime) {
    clear(webElement);
    Arrays.asList(value.toCharArray()).forEach(letter -> {
        typeOn(webElement, String.valueOf(letter));
        pause(waitBetweenLetters, unitTime);
    });
}

private void pause(long time, ChronoUnit unitTime) {
    try {
        Thread.sleep(Duration.of(time, unitTime).toMillis());
    } catch (InterruptedException ignore) {
    }
}

回答by Raghav

If you want to make your sendKeys more human like, I've used something like this:

如果你想让你的 sendKeys 更人性化,我使用了这样的东西:

private static void sendHumanKeys(WebElement element, String text) {
    Random r = new Random();
    for(int i = 0; i < text.length(); i++) {
        try {
            Thread.sleep((int)(r.nextGaussian() * 15 + 100));
        } catch(InterruptedException e) {}
        String s = new StringBuilder().append(text.charAt(i)).toString();
        element.sendKeys(s);
    }
}

It sends the keys with a 100ms delay, but only an average of 100ms. It creates a normal distribution with average 100ms and std. deviation 15ms.

它以 100 毫秒的延迟发送密钥,但平均只有 100 毫秒。它创建了一个平均 100ms 和 std 的正态分布。偏差 15ms。