如何在 Selenium 中统计页面中的链接总数?


可以通过 findElements() 方法统计页面中的链接总数。逻辑是返回标签名锚的 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://tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //Using tagname with anchor
      List<WebElement> links = driver.findElements(By.tagName("a"));
      System.out.println(“The number of links is “ + links.size());
      driver.close();
   }
}

更新于: 2020 年 6 月 10 日

14K+ 浏览量

开启你的 职业生涯

完成课程获取认证

开始
广告
© . All rights reserved.