如何在 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(); } }
廣告