如何使用 Selenium 一致地从输入元素中移除默认文本?
software testingautomation testingselenium web driver更新于 2026/2/8 6:37:17
我们可以使用 Selenium 一致地从输入元素中移除默认文本。clear 方法用于移除编辑框或文本区域中当前的值。
也可以使用 Keys.chord 方法以及 sendKeys 方法。Keys.chord 方法允许您一次传递多个键。键组或字符串将作为参数传递给该方法。
首先,将 Keys.CONTROL 和 a 作为参数传递给 Keys.chord 方法。然后将整个字符串作为参数传递给 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 RemDefaultVal{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// 识别元素
WebElement m = driver.findElement(By.id("gsc−i−id1"));
// 使用 clear() 删除默认值
m.clear();
driver.quit();
}
}
示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class RemDefaultValKeys{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// 识别元素
WebElement m = driver.findElement(By.id("gsc−i−id1"));
// 通过 Keys.Chord 发送 Ctrl+A
String st = Keys.chord(Keys.CONTROL, "a");
l.sendKeys(st);
// 发送 DELETE 键
l.sendKeys(Keys.DELETE);
driver.quit();
}
}

