如何從 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

更新時間:2020 年 9 月 18 日

8K+ 次觀看

啟動你的職業生涯

完成課程即可獲得認證

開始
Advertisement
© . All rights reserved.