1. 程式人生 > >selenium+java 獲取所有關於關鍵字元素並列印元素的個數 or 迴圈列印搜尋結果的標題

selenium+java 獲取所有關於關鍵字元素並列印元素的個數 or 迴圈列印搜尋結果的標題

public class ElementsDemo {

    public static void main(String[] args) throws InterruptedException {

        //驅動配置
        System.setProperty("webdriver.chrome.driver","D:\\driver\\chromedriver.exe"); 
        WebDriver driver =new ChromeDriver();
        driver.get("http://www.baidu.com");

        WebElement search_text =driver.findElement(By.id("kw"));
        search_text.sendKeys("selenium java");
        search_text.submit();
        Thread.sleep(2000);

        //匹配第一頁搜尋結果的標題 迴圈列印
        List<WebElement> search_result =driver.findElements(By.xpath("//div/div/h3"));

        //列印元素的個數
        System.out.println(search_result.size());

        //迴圈列印搜尋結果的標題
        for(WebElement result:search_result){
            System.out.println(result.getText());
        }

        System.out.println("----------------");

        //列印第n結果的標題
        WebElement text = search_result.get(search_result.size() -10);

        System.out.println(text.getText());

        driver.quit();

    }
}