如何在Selenium Webdriver的文本字段中一一输入字符? [英] How to enter characters one by one in to a text field in selenium webdriver?

查看:599
本文介绍了如何在Selenium Webdriver的文本字段中一一输入字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Selenium Webdriver的文本字段中一个接一个地输入字符?我已经使用了下面的代码,但是没有用

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

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

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

Can anybody suggest how to resolve this?

推荐答案

以下是我如何使用Selenium Webdriver(在Java中)逐字符发送字符的方法.通过这种方式,在后端,我会在每次按字母时验证输入中是否存在该字符.正常element.sendKeys()对我来说效果不佳,五分之二-缺少最后一个字母,我想Selenium Webdriver可能有问题,我不知道.试试下面的代码,它对我来说有100%的时间工作.

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.

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);
    }       
}

如您所见,我得到了需要键入的值,并且在for循环中,我将每个字符取回,将其转换为字符串,然后将其发送到文本框.另外,我正在搜索xpath,您可以将其更改为id或classname或任何您想要的名称.

As you see, I get the value needed to be typed and in the for loop, 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.

这篇关于如何在Selenium Webdriver的文本字段中一一输入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆