Selenium中如何获取编辑框的值?
software testingautomation testingselenium web driverjavascript更新于 2024/4/19 4:18:00
Selenium中我们可以通过以下方式获取编辑框的值 −
使用getText()方法。
使用JavascriptExecutor类。
使用方法getText()的代码实现。
示例
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 GetValueScripting { 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(12, TimeUnit.SECONDS); String text = driver.findElement(By.className("gsc-input")).getText(); System.out.println("Extracted text is " + text); driver.close(); } }
使用 JavascriptExecutor 类的代码实现。
示例
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; import org.openqa.selenium.JavascriptExecutor; public class ExtractValueScripting { 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(12, TimeUnit.SECONDS); // 创建 Javascript 对象 JavascriptExecutor js = (JavascriptExecutor)driver; // 发出命令以提取文本 String text = js.executeScript("return document.getElementById(' gsc-i-id1').value").toString(); System.out.println("Extracted text is" + text); driver.close(); } }