如何在 Selenium 中统计页面中的链接总数?
software testingautomation testingselenium web driver更新于 2026/2/10 15:37:17
可以使用 findElements() 方法统计页面中的链接总数。其逻辑是返回一个包含标签名 anchor 的 Web 元素列表,然后获取该列表的大小。
代码实现
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LinkCount {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//使用带有锚点的标签名
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println(“The number of links is “ + links.size());
driver.close();
}
}

