WebElement clear() 对文本框有何作用?
借助 Selenium webdriver,我们能够清除文本框中的内容。这通过clear()方法实现。此方法清除编辑框,并让该字段生效。
首先,我们需要借助 id、class、name、xpath 或 css 等定位器中的一种对元素进行识别,然后应用sendKeys()方法在其内部输入一些文本。之后我们需要应用 clear() 方法。为检查编辑框是否已清除,我们将采用 getAttribute() 方法,并将value 参数作为该方法的一个参数传递。应用 clear() 之后,我们将获得空白值。
我们考虑下方输入框,先在其中输入一些文本 - Selenium,再应用 clear() 方法。最后通过get_attribute()获取值。

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ClearEditBox{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
// identify element
WebElement p=driver.findElement(By.name("q"));
//enter text with sendKeys() then apply clear()
p.sendKeys("Selenium");
//getAttribute() to obtain value
String s= p.getAttribute("value");
System.out.println("Value before clear : " + s);
p.clear();
String n= p.getAttribute("value");
System.out.println("Value after clear : " + n);
driver.close();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP