Selenium WebDriver:我想用 sendKeys 覆盖字段中的值,而不是追加到它
我们可以用 Selenium webdriver 中的 sendKeys 覆盖字段中的值,而不是追加到它。这可以通过使用 Keys.chord 方法来实现。它返回一个字符串,并可以通过 sendKeys 方法应用于任何 Web 元素。
要覆盖一个值,我们首先要用 CTRL+A 键将其选中,然后再传递新的值。因此,Keys.CONTROL、A 和新值作为参数传递给 Keys.chord 方法。
语法
String n = Keys.chord(Keys.CONTROL, "A");
WebElement l = driver.findElement(By.name("q"));
l.sendKeys(n, "Tutorialspoint");示例
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;
import org.openqa.selenium.Keys;
public class OverWriteVals{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.google.com/");
//identify element
WebElement m = driver.findElement(By.name("q"));
m.sendKeys("Selenium");
// Keys.chord to pass multiple strings
String n = Keys.chord(Keys.CONTROL, "A");
//overwrite value
m.sendKeys(n, "Tutorialspoint");
String s= m.getAttribute("value");
System.out.println("Value after overwrite: " + s);
driver.quit();
}
}输出

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