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(); } }
輸出
廣告