如何使用 selenium 為 web 元素的“value”賦值?
我們可以使用 Selenium webdriver 來為輸入 web 元素賦值。我們可以藉助 sendKeys 方法來向輸入欄位輸入文字。要輸入的值作為引數傳遞給該方法。
語法
driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");我們還可以使用 Selenium 中的 Javascript 執行器來執行輸入編輯框文字之類的 web 操作。我們將使用 executeScript 方法,並將 引數 index.value='<要輸入的值>' 和 webelement 作為引數傳遞給該方法。
語法
WebElement i = driver.findElement(By.id("id"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", i);示例
程式碼實現
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
public class SetValue{
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://tutorialspoint.tw/about/about_careers.htm");
// identify element
WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
l.sendKeys("Selenium");
// obtain the value entered with getAttribute method
System.out.println("Value entered is: " +l.getAttribute("value"));
driver.close();
}
}示例
使用 Javascript 執行器的程式碼實現。
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetValueJS{
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://tutorialspoint.tw/about/about_careers.htm");
// identify element
WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
// Javascript Executor class with executeScript method
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", l);
System.out.println("Value entered is: " +l.getAttribute("value"));
driver.close();
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP