9.selenium之定位一组元素

我们已经学习了8种定位方法, 那8种定位方法是针对单个元素定位的, WebDriver还提供了另外8种用于定位一组元素的方法。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Keys;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

findElements(By.id())
findElements(By.name())
findElements(By.className())
findElements(By.tagName())
findElements(By.linkText())
findElements(By.partialLinkText())
findElements(By.xpath())
findElements(By.cssSelector())

定位一组元素的方法与定位单个元素的方法类似,唯一的区别是在单词 findElement 后面多了一个 s 表示复数。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;


public class ElementsDemo {

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

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com/");

        WebElement search_text = driver.findElement(By.id("kw"));
        search_text.sendKeys("selenium");
        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();
    }
}
结果如下:
12 selenium__软件测试培训_免费领取试听课程 自动化测试工具selenium-新手入门宝典-实战性强 Selenium(WEB自动化工具)_百度百科 Selenium automates browsers. That's it!官方 selenium安装一款任何网站都能抓取的爬虫工具 selenium库的基本使用 - 简书 selenium中文网 | selenium安装、selenium使用、selenium中文... Python Selenium库的使用_凯耐的博客-CSDN博客_selenium selenium_百度翻译 selenium用法详解_天涯笨熊的博客-CSDN博客_selenium GitHub - SeleniumHQ/selenium: A browser automation framework... Selenium Projects -------我是分割线--------- Selenium(WEB自动化工具)_百度百科
原文地址:https://www.cnblogs.com/peiminer/p/13564560.html