Selenium的组成及特点

 一、Selenium简介

   Selenium是一个用于Web应用程序自动化测试工具Selenium测试直接运行在浏览器中,就像真正的用户在
 操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。
 适用于自动化测试,js动态爬虫(破解反爬虫)等领域。

提供了丰富的测试函数,用于实施web自动化的一款流行的测试工具,直接运行于浏览器中,真实模拟用户的业务行为

扩展性比较好,支持语言比较多,简单快捷

实际上不是一个 测试工具,是一个工具集,主要由三个核心组件组成:Selenium IDE,Selenium RC(Remote Control) 及Selenium Grid

1.1、自动化测试简介

测试用例主要包括以下几个内容:1、用例序号  2、用例标题 3、重要级别 4、测试环境  5、操作步骤  6、预期结果 

Selenium:流行的开源web自动化测试工具, 直接运行在浏览器中,就像真正的用户在操作一样,支持的的浏览器包括IE,Firefox,Chrom等

自动化测试的优点:快速回归、脚本重用、代替人的重复工作、提高工作效率

缺点:只能检查主要的问题,没有办法发现新的问题,工作量比较大

     
 二、Selenium组成

     1)Selenium IDE:嵌入到Firefox浏览器中的一个插件,实现简单的浏览器操作录制与回放功能,主要用于快速创建BUG及重现脚本,可转化为多种语言
     2)Selenium RC: 核心组件,支持多种不同语言编写自动化测试脚本,通过其服务器作为代理服务器去访问应用,达到测试的目的
     3)
Selenium WebDriver(重点):一个浏览器自动化框架,它接受命令并将它们发送到浏览器。它是通过特定于浏览器的驱动程序实现的。它直接与浏览器通信并对其进行控制。Selenium WebDriver支持各种编程语言,如Java、C# 、PHP、Python、Perl、Ruby
     4)Selenium grid:测试辅助工具,用于做分布式测试,可以并行执行多个测试任务,提升测试效率。


 三、Selenium特点

     1)开源、免费
     2)多浏览器支持:FireFox、Chrome、IE、Opera、Edge;
     3)多平台支持:Linux、Windows、MAC;
     4)多语言支持:Java、Python、Ruby、C#、JavaScript、C++;
     5)对Web页面有良好的支持;
     6)简单(API 简单)、灵活(用开发语言驱动);
     7)支持分布式测试用例执行。


 四、案例演示

     爬虫:数据采集、数据清晰、数据分析!!!

     4.1 java爬虫入门

     1.下载驱动包

     http://chromedriver.storage.googleapis.com/index.html

     2.创建项目并导入依赖

 <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
     </dependency>

     3.入门

   //设置驱动
     System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");
     //创建驱动
     WebDriver driver=new ChromeDriver();
     //与将要爬取的网站建立连接
     driver.get("https://www.baidu.com");
     //关闭浏览器
     driver.close();
     //释放资源
     driver.quit();

     4.2 相关API

     1.元素选择方式
     
     1)Class选择:driver.findElement(By.className("s_ipt"));
     2)ID选择:   driver.findElement(By.id("kw"));
     3)name选择: driver.findElement(By.name("wd"));
     4)tag选择:  driver.findElements(By.tagName("input"));
     5)link选择: driver.findElement(By.linkText("地图"));
     6)Partial link选择(a标签文本内容模糊匹配):driver.findElement(By.partialLinkText("使用百"));
     7)css选择器:driver.findElement(By.cssSelector("#kw"));
     8)xpath选择:driver.findElement(By.xpath("//*[@id=\"kw\"]"));

     2.获取单个元素:driver.findElement

     3.获取多个元素:driver.findElements

     4.输入内容:input.sendKeys("java");

     5.元素点击:element.click();

     6.获取元素属性:nextPageEle.getAttribute("class")

     7.获取标签文本内容:titleEle.getText()

 代码演示:

package com.zking;

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 Demo {

    public static void main(String[] args) {
        //设置驱动
        System.setProperty("webdriver.chrome.driver","C:\\Users\\zjjt\\Downloads\\chromedriver.exe");
        //创建驱动
        WebDriver driver=new ChromeDriver();
        //与将要爬取的网站建立连接
        driver.get("https://www.baidu.com");
        //关闭浏览器
//        driver.close();
//        //释放资源
//        driver.quit();

//        1)Class选择:driver.findElement(By.className("s_ipt"));
//            WebElement element=driver.findElement(By.className("s_btn"));
//        System.out.println(element.getAttribute("value"));

//        2)ID选择:   driver.findElement(By.id("kw"));
//        WebElement element=driver.findElement(By.id("kw"));
//        System.out.println(element.getAttribute("class"));
//
//        3)name选择: driver.findElement(By.name("wd"));
//        WebElement element=driver.findElement(By.name("wd"));
//        System.out.println(element.getAttribute("maxlength"));

//        4)tag选择:  driver.findElements(By.tagName("input"));
//        List<WebElement> elements = driver.findElements(By.tagName("a"));
//        for (WebElement element:elements){
//            System.out.println(element.getText().trim());
//        }
//        5)link选择: driver.findElement(By.linkText("地图"));
//        WebElement elemen = driver.findElement(By.linkText("网盘"));
//        System.out.println(elemen.getText());
//        6)Partial link选择(a标签文本内容模糊匹配):driver.findElement(By.partialLinkText("使用百"));
//        List<WebElement> elements = driver.findElements(By.partialLinkText("人"));
//        for (WebElement element:elements){
//            System.out.println(element.getText());
//        }
//        7)css选择器:driver.findElement(By.cssSelector("#kw"));
//        List<WebElement> elements = driver.findElements(By.cssSelector("#hotsearch-content-wrapper > li:nth-child(1)"));
//        for(WebElement element:elements){
//            System.out.println(element.getText());
//        }
//        8)xpath选择:driver.findElement(By.xpath("//*[@id=\"kw\"]"));
//        WebElement element = driver.findElement(By.xpath("//*[@id=\"kw\"]"));
//        System.out.println(element.getAttribute("value"));

        driver.findElement(By.id("kw")).sendKeys("java");
        driver.findElement(By.id("su")).click();
    }
}

 五:Selenium爬取JD商品信息

     1.初始化

  //将驱动加载到Java的JVM虚拟机中
     System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");
     /************************** 方式一:不打开浏览器 **************************/
     //定义浏览器参数
     ChromeOptions chromeOptions = new ChromeOptions();
     //设置不打开浏览器
     chromeOptions.addArguments("--headless");
     //初始化驱动
     driver = new ChromeDriver(chromeOptions);

     /************************** 方式二:打开浏览器 **************************/
     //初始化驱动
     driver = new ChromeDriver();

     2.点开JD网址并指定关键字搜索

  driver.get("https://www.jd.com/");
     //输入关键字衣服
     driver.findElement(By.id("key")).sendKeys("衣服");
     //点击搜索按钮
     driver.findElement(By.cssSelector("button.button")).click();

     3.设定睡眠时间(可根据网络速度实际调整)

   Thread.sleep(i * 1000);

     4.查找商品列表并获取相关信息
     
     //*[@id="J_goodsList"]/ul/li

     商品信息:className="p-name"
     商品价格:className="p-price"

package com.zking;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

public class Demo01 {
    public static void main(String[] args) {
        //设置驱动
        System.setProperty("webdriver.chrome.driver","C:\\Users\\zjjt\\Downloads\\chromedriver.exe");
        //创建驱动
        WebDriver driver=new ChromeDriver();
        //与将要爬取的网站建立连接
        driver.get("https://www.jd.com");

        //模拟输入查询条件
        driver.findElement(By.id("key")).sendKeys("手表");
        //模拟点击事件,实现商品查询
        driver.findElement(By.cssSelector("button.button")).click();

        sleep(3);

        //执行js,滚动条下拉到最底
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)");

        sleep(3);


        //获取数据
        List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"J_goodsList\"]/ul/li"));
        //循环遍历
        for (WebElement element : elements) {
            //获取商品价格·
            WebElement price = element.findElement(By.className("p-price"));
            //获取商品名称
            WebElement name = element.findElement(By.className("p-name"));
            System.out.println("【"+price.getText()+"】-"+name.getText().trim());
        }
        //  关闭浏览器&&释放资源
        driver.close();
        driver.quit();
    }



    /**
     * 获取数据模拟等待时间
     * @param second
     */
    private  static void sleep(int second){
        try {
            Thread.sleep(second*1000L);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


 二、Selenium爬取图片

package com.zking;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Demo02 {

    //定义获取图片的下载地址集合
    private static List<String> paths=new ArrayList<>();

    //定义图片下载网址
    private static final String PATH="https://www.139ys.com/";

    //下载图片保存到指定的目录
    private static final String DIR="E:\\images\\";

    private static void getImages(){
        //设置驱动
        System.setProperty("webdriver.chrome.driver","C:\\Users\\zjjt\\Downloads\\chromedriver.exe");
        //创建驱动
        WebDriver driver=new ChromeDriver();
        //与将要扒取的网站建立连接
        driver.get(PATH);

        sleep(1);
        //获取图片资源
        List<WebElement> elements = driver.findElements(By.xpath("/html/body/div[2]/div/div[1]/div/div[2]/ul/li"));
        //循环遍历获取图片资源
        for (WebElement element : elements) {
            //获取a标签
            WebElement a = element.findElement(By.tagName("a"));
           paths.add(a.getAttribute("data-original"));

        }
        //  关闭浏览器&&释放资源
        driver.close();
        driver.quit();
    }

    public static void main(String[] args) {
        getImages();
        for (String str : paths) {
            System.out.println(str);
            saveImg(str);
        }
    }

    private static void saveImg(String path){
        try{
            sleep(1);
            //定义图片名称
            String img =System.currentTimeMillis()+".jpg";
            URL url=new URL(path);
            //定义输入流
            DataInputStream is = new DataInputStream(url.openStream());
            //定义输出流
            FileOutputStream fileOutputStream = new FileOutputStream(new File(DIR + img));
            //定义每次读取长度
            int len=0;
            //定义每次读取大小
            byte[] size=new byte[1024];
            //循环读流写流
            while ((len=is.read(size))!=-1){
                fileOutputStream.write(size,0,len);
            }
            //关闭
            is.close();
            fileOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();;
        }
    }

    /**
     * 获取数据模拟等待时间
     * @param second
     */
    private  static void sleep(int second){
        try {
            Thread.sleep(second*1000L);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值