如何在 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.tw/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+ 瀏覽量

開啟你的 職業生涯

完成課程獲取認證

開始
廣告