如何从 Selenium 获取元素的属性?
seleniumautomation testingtesting tools更新于 2026/2/11 12:22:17
我们可以在 Selenium webdriver 中获取元素的属性。getAttribute() 方法用于获取 HTML 文档中属性的值。在 HTML 代码中,属性及其值以键值对的形式出现。
一些常见的 HTML 属性包括 disabled、alt、id、href、style、title 和 src。我们要获取的属性值将作为参数传递给该方法。
我们来考虑一段 HTML 代码,我们将获取它的 src 属性。 src 属性的值应为 /about/images/logo.png。

示例
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 GetSrcAttribute{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u = "https://www.tutorialspoint.com/about/about_careers.htm"driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// 识别元素
WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
// 使用 getAttribute() 获取 src 属性
System.out.println("Src attribute is : " + t.getAttribute("src"));
driver.close();
}
}
输出

