如何在 Selenium 中從 href 連結中獲取屬性值?


我們可以在 Selenium 中從 href 連結中獲取屬性值。首先,我們必須先使用 css、id、class 等定位器來識別具有錨標記的元素。

接下來,我們將使用getAttribute 方法,並將href 作為引數傳遞給該方法。讓我們研究一個具有 href 屬性的錨標記元素。此處,href 的值應包含/about/about_team.htm

示例

程式碼實現。

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 HrefValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/about/about_team.htm");
      // identify element
      WebElement l = driver.findElement(By.linkText("Team"));
      // href value from getAttribute()
      String v = l.getAttribute("href");
      System.out.println("Href value of link: "+ v);
      driver.close();
   }
}

輸出

更新於:2020 年 12 月 28 日

12K+ 次觀看

職業起航

完成課程,獲得認證

開始入門
廣告