如何使用 Selenium 删除文本字段中的默认值?
seleniumautomation testingtesting tools更新于 2026/2/11 16:22:17
我们可以使用 Selenium WebDriver 删除文本字段中的默认值。有多种方法可以做到这一点。我们可以使用 clear() 方法,该方法可以重置编辑框或文本区域字段中已有的值。
我们可以将 Keys.chord() 方法与 sendKeys() 结合使用。Keys.chord() 方法可以帮助同时按下多个按键。它接受按键序列或字符串作为方法的参数。
要删除默认值,它需要 Keys.CONTROL、"a" 作为参数。然后,该字符串将作为参数发送给 sendKeys() 方法。最后,我们必须将 Keys.DELETE 传递给 sendKeys() 方法。
让我们考虑下面的编辑字段,我们将在其中删除输入值。

示例
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 DelDefaultVal{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// 识别元素
WebElement l = driver.findElement(By.id("gsc-i-id1"));
// 输入文本
l.sendKeys("Selenium");
// 使用 clear() 删除默认值
l.clear();
driver.quit()
}
}
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class DelDefaultValue{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// 识别元素
WebElement l = driver.findElement(By.id("gsc-i-id1"));
// 输入文本
l.sendKeys("Selenium");
// 通过 Keys.Chord() 发送 Ctrl+a
String s = Keys.chord(Keys.CONTROL, "a");
l.sendKeys(s);
// 发送 DELETE 键
l.sendKeys(Keys.DELETE);
driver.quit()
}
}

