如何使用 Selenium 獲取特定類中 href 的內容?


我們可以使用 Selenium webdriver 獲取特定目標類中的 href 內容。首先,我們必須使用諸如 xpath、css 或 classname 等定位器,定位具有特定類屬性值的帶有 anchor 標籤的元素。

然後,我們必須藉助getAttribute方法,並將 href作為引數傳遞給該方法。讓我們看一個帶有具有 class 和 href 屬性的 anchor 標籤的元素的 html 程式碼。該元素的 href 值應該是 /account/register?hl=en

示例

程式碼實現。

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 HrefVal{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element with specific class value
      WebElement m= driver.findElement(By.className("login-registrationBoldLink"));
      // getAttribute() to href value
      String val = m.getAttribute("href");
      System.out.println("Href value of targeted: "+ val);
      driver.close()
   }
}

輸出

更新於: 2020-10-26

805 瀏覽量

立即開始你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.