I've been trying to fix this issue for a while now, none of the existing questions help. I'm using the node implementation of Selenium WebDriver , version ^4.0.0-alpha.1 and testing it on Chrome using the latest ChromeDriver.
I'm trying to clear the text of an <input/>
, whose type="email"
. WebDriver has a built in command for this, but when I execute it the input doesn't clear (and there's no error):
// This populates the text field, no problem
driver.findElement(By.id("model-auth-email")).sendKeys("test@gmail.com");
// This is executed without error, but nothing happens, text field isn't cleared
driver.findElement(By.id("model-auth-email")).clear();
I can't use the CTRL + a & BACKSPACE method since I'm using a Mac and it would be CMD + a . And ChromeDriver has had (still unresolved) issues supporting the native OSX CMD button input for like 6 years, according the various threads I could find.
I could also do something like loop BACKSPACE inputs until it's cleared, though that's pretty hacky.
Any ideas on why .clear()
is silently not working?
我有同样的问题, .clear() 或 CTRL+'a' 对我不起作用,这个工作得很好:
driver.execute_script("arguments[0].value = '';", text_input)
What seems to be working for us is to:
select()
method of the <input>
element. Here's a clear
function that will do just that:
async function clear(drv, web_elt) {
await drv.executeScript(elt => elt.select(), web_elt);
await web_elt.sendKeys(Key.BACK_SPACE);
}
Whereby:
drv
is an instance of WebDriver
web_elt
is an instance of WebElement
executeScript
is stringified and receives the <input>
element wrapped in web_elt
as a parameter Find below a demo and the full code for it.
This is running on Node.js 11 with selenium-webdriver
v4.
Make sure your chromedriver is in your PATH then run node index.js
// index.js
const path = require('path');
const wd = require('selenium-webdriver');
const {Key} = wd;
const driver =
(new wd.Builder)
.forBrowser(wd.Browser.CHROME)
.build();
async function clear(drv, web_elt) {
await drv.executeScript(elt => elt.select(), web_elt);
await web_elt.sendKeys(Key.BACK_SPACE);
}
async function run(drv) {
await drv.get('file://' + path.join(__dirname, 'index.html'));
await drv.sleep(1000);
await clear(drv, drv.findElement({css: 'input'}));
await drv.sleep(1000);
await clear(drv, drv.findElement({css: 'textarea'}));
await drv.sleep(1000);
await drv.quit();
}
run(driver);
<!-- index.html -->
<html>
<body>
<p>
<input type="text" value="Hello World!"/>
</p>
<p>
<textarea cols="30" rows="10">Hello World!</textarea>
</p>
</body>
</html>
From Webdriver document, findElement will return a promise, so you can try:
driver.findElement(By.id("model-auth-email"))
.then((el) => {
el.clear()
})
.catch(e => {
throw e;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.