如何使用 Selenium 获取某个目标类中 href 的内容?

seleniumautomation testingtesting tools更新于 2026/2/10 8:52:17

我们可以使用 Selenium WebDriver 获取某个目标类中 href 的内容。首先,我们需要借助 xpath、css 或 classname 等定位器,找到带有特定 class 属性值的 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);
      // 识别具有特定类值的元素
      WebElement m= driver.findElement(By.className("login-registrationBoldLink"));
      // getAttribute() 获取 href 值
      String val = m.getAttribute("href");
      System.out.println("Href value of targeted: "+ val);
      driver.close()
   }
}

输出


相关文章