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 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();

    }
}

 

你可能感兴趣的:(基础篇,持续更新,..)