如何在 Selenium 中提取元素的属性值?
software testingautomation testingselenium web driver更新于 2026/2/10 15:07:17
我们可以借助 getAttribute() 方法提取 Selenium 中元素的属性值。找到元素后,即可使用此方法获取元素的属性值并将其赋值给变量。
示例
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 java.util.List;
public class AttributeType {
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);
//使用 id 标签名 属性组合进行 CSS 表达式
WebElement button = driver.findElement(By.cssSelector("input[name=’search’]"));
// 获取 type 属性并在控制台中打印
String buttontype = button.getAttribute(“type”);
System.out.println(“Attribute value is “ + buttontype);
driver.close();
}
}

