我有一个长字符串要测试,sendKeys()
需要太长时间。当我尝试设置text
程序崩溃的值时。我知道Selenium sendKeys()
是测试实际用户输入的最佳方式,但对于我的应用程序,它需要花费太多时间。所以我试图避免它。
有没有办法立即设置值?
请参阅此快速示例:
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);
答案 0 :(得分:46)
尝试使用executeScript
方法设置元素的值:
webdriver.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
答案 1 :(得分:7)
使用.executeScript()
延伸到Andrey-Egorov的正确答案,以结束我自己的问题示例:
inputField = driver.findElement(webdriver.By.id('gbqfq'));
driver.executeScript("arguments[0].setAttribute('value', '" + longstring +"')", inputField);
答案 2 :(得分:7)
感谢Andrey Egorov,在我的情况下python setAttribute
无效,但我发现我可以直接设置属性,
试试这段代码:
driver.execute_script("document.getElementById('q').value='value here'")
答案 3 :(得分:3)
向文本字段发送大量重复字符的另一种方法(例如,测试字段允许的最大字符数)是键入几个字符,然后重复复制并粘贴它们:
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'));
}
}
不幸的是,除非启用REQUIRE_WINDOW_FOCUS
(这可能导致其他问题),否则按CTRL似乎不适用于IE,但它适用于Firefox和Chrome。
答案 4 :(得分:2)
感谢Andrey-Egorov和answer,我已经设法在C#中做到了
IWebDriver driver = new ChromeDriver();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string value = (string)js.ExecuteScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");
答案 5 :(得分:1)
如果要使用某些变量,可以使用以下方式:
String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
答案 6 :(得分:0)
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");
答案 7 :(得分:0)
简而言之,这是对我有用的代码:)
WebDriver driver;
WebElement element;
String value;
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
答案 8 :(得分:0)
谢谢大家,这是我在 Java 中设法做到这一点的方法
public static void sendKeysJavascript(By element, String keysToSend) {
WebElement el = driver.findElement(element);
JavascriptExecutor ex = (JavascriptExecutor) driver;
ex.executeScript("arguments[0].value='"+ keysToSend +"';", el);
}