如何使用 Selenium 获取 Web 元素的属性值(使用 Java 或 Python)?
我们可以使用 getAttribute 方法以及 Selenium webdriver 获取 Web 元素的属性值,然后将我们要获取其值的属性作为参数传递给该方法。
在 html 代码中,一个元素被定义为具有键值对的属性及其值。让我们尝试获取页面的以下元素的 class - heading −

语法
WebElement t =driver.findElement(By.xpath("//li[text()='About Tutorialspoint']"));
String s = t.getAttribute("class");示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class AttribtValue{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify element with xpath
WebElement t =driver.
findElement(By.xpath("//li[text()='About Tutorialspoint']"));
//get value of class attribute
String s = t.getAttribute("class");
System.out.println("Class attribute value is : " + s);
driver.close();
}
}输出

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