如何在 Selenium Webdriver 中获取某个元素的属性值?
我们可以获得元素在 Selenium Webdriver 中的属性值。这通过 getAttribute 方法实现。在 html 文档中,每个元素通过其标签名称以及带值的元素属性进行标识。要获取属性值,我们必须将元素属性作为参数传递给 getAttribute 方法。
让我们看看一个元素的 html 代码并获得其 src 属性的值。其 src 属性的值应为 /about/images/logo.png。

示例
代码实现。
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 AttributeVal{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//application launch
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement l=driver.findElement(By.className("tp-logo"));
// getAttribute() to get src value
String value = l.getAttribute("src");
System.out.println("Src attribute is: "+ value);
//browser close
driver.close()
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP