如何使用 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.tw/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