如何在 Selenium 中从文本框获取已输入的文本?
我们可以使用 Selenium WebDriver 从文本框中获取已输入的文本。要获取 html 文档中元素的 value 属性,我们必须使用 getAttribute() 方法。然后,value 作为参数传递给该方法。
让我们考虑一个文本框,我们在其中输入了一些文本,然后想要获取已输入的文本。

如果我们监视元素,我们会发现 html 代码中此元素没有 value 属性。

在该字段中输入文本后,我们可以使用 getAttribute() 方法获取已输入的文本。
示例
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 GetValAttribute{
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://tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// identify element
WebElement l = driver.findElement(By.id("gsc-i-id1"));
// enter texts
l.sendKeys("Selenium");
// get value attribute with getAttribute()
String val = l.getAttribute("value");
System.out.println("Entered text is: " + val);
driver.quit()
}
}输出

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