设置input值而不是sendKeys() – selenium webdriver nodejs

我有一个很长的string来testing和sendKeys()需要太长时间。 当我试图设置text的值时,程序崩溃。 我知道Selenium sendKeys()是testing实际用户input的最好方法,但是对于我的应用程序来说,它需要太多的时间。 所以我试图避免它。

有没有一种方法可以马上设置值?

看这个简单的例子:

 var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); driver.get('http://www.google.com'); // find the search input field on google.com inputField = driver.findElement(webdriver.By.name('q')); var longstring = "test"; // not really long for the sake of this quick example // this works but is slow inputField.sendKeys(longstring); // no error but no values set inputField.value = longstring; // Output: TypeError: Object [object Object] has no method 'setAttributes' inputField.setAttributes("value", longstring); 

尝试使用executeScript方法设置元素的值:

 webdriver.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')"); 

从Andrey-Egorov的正确答案扩展使用.executeScript()来结束我自己的问题示例:

 inputField = driver.findElement(webdriver.By.id('gbqfq')); driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField); 

感谢Andrey Egorov,在我的情况下python setAttribute不工作,但我发现我可以直接设置属性,

试试这个代码:

 driver.execute_script("document.getElementById('q').value='value here'") 

将大量重复字符发送到文本字段(例如,testing字段允许的最大字符数)的另一种方法是键入几个字符,然后重复复制并粘贴它们:

 inputField.sendKeys('0123456789'); for(int i = 0; i < 100; i++) { inputField.sendKeys(Key.chord(Key.CONTROL, 'a')); inputField.sendKeys(Key.chord(Key.CONTROL, 'c')); for(int i = 0; i < 10; i++) { inputField.sendKeys(Key.chord(Key.CONTROL, 'v')); } } 

不幸的是按CTRL似乎不适用于IE浏览器,除非REQUIRE_WINDOW_FOCUS被启用(这可能会导致其他问题),但它适用于Firefox和Chrome。

感谢Andrey-Egorov和这个答案 ,我设法在C#

 IWebDriver driver = new ChromeDriver(); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");