如何在 Selenium 中获取 href 链接的属性值?
seleniumautomation testingtesting tools
我们可以在 Selenium 中获取 href 链接的属性值。首先,我们必须借助 css、id、class 等定位器来识别带有 anchor 标签 的元素。
接下来,我们将使用 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://www.tutorialspoint.com/about/about_team.htm");
// 识别元素
WebElement l = driver.findElement(By.linkText("Team"));
// 来自 getAttribute() 的 href 值
String v = l.getAttribute("href");
System.out.println("Href value of link: "+ v);
driver.close();
}
}
输出


