如何從 Selenium 獲取元素屬性?
我們可以在 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://tutorialspoint.tw/about/about_careers.htm"driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
// get src attribute with getAttribute()
System.out.println("Src attribute is : " + t.getAttribute("src"));
driver.close();
}
}
Output

Advertisement
資料結構
計算機網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP