Selenium的简单例子:

本文介绍了使用Selenium进行自动化测试的实际操作,包括启动浏览器、访问网页、执行JavaScript、处理弹窗、切换frame、检查元素等。通过具体的测试用例展示了如何操作网页元素,如点击、输入、验证页面内容等。此外,还涉及了错误处理和测试断言,确保测试用例的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package android1708selenium;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class ExecCase {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        // 设置驱动
        System.setProperty("webdriver.chrome.driver","D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        // 启动浏览器
        WebDriver driver=new ChromeDriver();
        // 访问禅道首页
        driver.get("http://127.0.0.1/index.php");
        // 点击“开源版”
        driver.findElement(By.id("zentao")).click();
        // 在登录页面输入用户名,密码,点击登录按钮
        driver.findElement(By.id("account")).sendKeys("admin");
        driver.findElement(By.name("password")).sendKeys("123456.");
        driver.findElement(By.id("submit")).click();
        // 登录后,点击一级导航的“测试”
        driver.findElement(By.xpath("//nav[@id='mainmenu']/ul/li[4]/a")).click();
        // 点击二级导航的“用例”
        driver.findElement(By.xpath("//nav[@id='modulemenu']/ul/li[3]/a")).click();
        // 点击第一条用例的标题,进入用例的详情页
        driver.findElement(By.xpath("//div[@id='datatable-caseList']/div[2]/div/div/table/tbody/tr[1]/td[4]/a")).click();
        // 在用例的详情页点击“执行”按钮,运行测试用例
        driver.findElement(By.xpath("//a[@class='btn runCase' and @href='/zentao/testtask-runCase-0-65-1.html' and @data-width='95%']")).click();
        // 执行用例加载比较慢,设置一个等待时间,以免找不到元素
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 把webdriver定位到用例执行窗口frame中
        driver.switchTo().frame("modalIframe");
        // 取执行用例之前的用例id,供重新查看时验证用例一致使用
        String execcaseid = driver.findElement(By.xpath("//div[@id='titlebar']/div/span/strong")).getText();
        // 在测试用例执行之前,我取这个测试有用例已存在的结果数量,
        String beforeExecCaseNumberStr = driver.findElement(By.xpath("//div[@id='casesResults']/table/caption/strong/span/span")).getText();
        int beforeExecCaseNumberInt = Integer.parseInt(beforeExecCaseNumberStr);
        // 依次取出用例执行之前的所有记录,并放置一个list中。
        // 定义一个list,里面放执行用例之前的结果数据
        List<String> beforeExecCaselist = new ArrayList();
        for(int i=1;i<(2*beforeExecCaseNumberInt);i=i+2){
            String caseResultXpth = "//div[@id='casesResults']/table/tbody/tr["+i+"]/td[2]";
            String tempstr = driver.findElement(By.xpath(caseResultXpth)).getText();
            beforeExecCaselist.add(tempstr);
        }
        
        // 在用例执行窗口,点击“保存”按钮,执行用例的通过操作。
        driver.findElement(By.id("submit")).click();
        // 点击“保存”按钮后,涉及保存数据的执行,需要增加一个等待时间,以免下一步找不到元素。
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 点击“保存”按钮,即执行用例通过操作。此时frame跳转到下一条用例窗口,需要再返回当前用例窗口
        // 点击窗口中的“上一个”,即返回刚执行的用例窗口
        driver.findElement(By.id("pre")).click();
        // 点击“上一个”按钮后,涉及读取数据的执行,需要增加一个等待时间,以免下一步找不到元素。
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 取跳转窗口的用例id,来验证是不是刚才执行过的用例
        String getbackcaseid = driver.findElement(By.xpath("//div[@id='titlebar']/div/span/strong")).getText();
        if(!getbackcaseid.equals(execcaseid)){
            Assert.assertFalse("用来判断执行是否成功的两个case不一致,无法判断", true);
        }
        // 在测试用例执行之后,我取这个测试有用例已存在的结果数量,
        String behindExecCaseNumberStr = driver.findElement(By.xpath("//div[@id='casesResults']/table/caption/strong/span[1]/span")).getText();
        int behindExecCaseNumberInt = Integer.parseInt(behindExecCaseNumberStr);
        
        // 执行之后和执行之前的结果应该只差一次,若不满足就证明数据有问题,就没有继续执行的必要了
        if(behindExecCaseNumberInt-beforeExecCaseNumberInt!=1){
            Assert.assertFalse("执行用例前和执行用例后的结果数量不等于1,那么此次用例中存在脏数据,用例设置为执行失败需要重新验证", true);
        }
        // 依次取出用例执行之后的所有记录,并放置一个list中。
        for(int i=1;i<(2*behindExecCaseNumberInt);i=i+2){
            String caseResultXpth = "//div[@id='casesResults']/table/tbody/tr["+i+"]/td[2]";
            String tempstr = driver.findElement(By.xpath(caseResultXpth)).getText();
        //    beforeExecCaselist.add(tempstr);
            // 把执行用例之后的每个结果,都和之前执行的执行结果集list做判断,得到新执行生成的结果
            if(!beforeExecCaselist.contains(tempstr)){
                // 通过for里判断得到最新用例执行结果的时间来定位此用例的执行结果文字
                String caseResultTextXpth = "//div[@id='casesResults']/table/tbody/tr["+i+"]/td[5]/strong";
                String caseResultText = driver.findElement(By.xpath(caseResultTextXpth)).getText();
                // 判断此次执行用例的预期结果是否与执行步骤实际结果一致。
                Assert.assertEquals("通过", caseResultText);
            }
        }
        System.out.println("执行到最后了");
        driver.close();
    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import java.io.IOException;

import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ExecDos {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        System.setProperty("webdriver.chrome.driver", "D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com");
        
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        String dosstr="tskill chrome";
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(dosstr);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ExecJS {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        // 把chromedriver赋值给系统的属性
        System.setProperty("webdriver.chrome.driver", "D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        // 实例化一个浏览器对象
        WebDriver driver = new ChromeDriver();
        // 打开百度首页
        driver.get("https://www.baidu.com");
        // 用javascript在搜索框中填入搜索关键词
        String js = "document.getElementById(\"kw\").value=\"网易\"";
        if(driver instanceof JavascriptExecutor){
            ((JavascriptExecutor) driver).executeScript(js);
        }
        // 点击“百度一下”
        driver.findElement(By.id("su")).click();
        // 加一个等待时间,等待搜索结果页面加载完毕
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 取得搜索结果字符串
        String resulttext = driver.findElement(By.xpath("//div[@id='container']/div[2]/div/div[2]/span")).getText();
        System.out.println(resulttext);
        // 用split切割字符串,取得搜索结果的数字
        String[] resultarr = resulttext.split("[约|个]");
        // 切割完成后,数字是在数组的第二个元素
        System.out.println(resultarr[1]);
        // 测试结束,关闭浏览器
        driver.close();
        
    }

}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.Alert;
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;

public class MakeCase {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        // 设置驱动
        System.setProperty("webdriver.chrome.driver","D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        // 启动浏览器
        WebDriver driver=new ChromeDriver();
        // 访问禅道的url
        driver.get("http://127.0.0.1/index.php");
        // 点击“开源版”连接
        driver.findElement(By.id("zentao")).click();
        // 输入用户名和密码,并点击登录按钮
        driver.findElement(By.id("account")).sendKeys("admin");
        driver.findElement(By.name("password")).sendKeys("123456.");
        driver.findElement(By.id("submit")).click();
        // 取登录后页面中左上角的“易软天创管理系统”几个字验证
        String loginconfirm = driver.findElement(By.id("companyname")).getText();
        String loginexpect = "易软天创项目管理系统";
        // 判断 “易软天创管理系统”是否正确显示
        Assert.assertTrue("登录失败", loginexpect.equals(loginconfirm));
        
        // 点击一级导航的“测试”
        driver.findElement(By.xpath("//nav[@id='mainmenu']/ul/li[4]/a")).click();
        // 点击二级导航的“用例”
        driver.findElement(By.xpath("//nav[@id='modulemenu']/ul/li[3]/a")).click();
        // 点击用例列表页面右上角的“建用例”按钮
        driver.findElement(By.xpath("//div[@id='createActionMenu']/a")).click();
        // 生成一个时间戳,放在用例标题里
        SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmss");
        Date date = new Date();
        String timestr = sdf.format(date);
        // 填写用例标题
        String titlestr = "验证用例标题"+timestr;
        driver.findElement(By.id("title")).sendKeys(titlestr);
        // 填写有用例步骤
        driver.findElement(By.name("steps[1]")).sendKeys("用例操作步骤");
        // 填写用例预期结果
        driver.findElement(By.name("expects[1]")).sendKeys("预期的用例结果");
        // 拉动滚动条,使提交按钮显示在屏幕中。
        WebElement wb = driver.findElement(By.id("submit"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", wb);
        // 点击保存按钮,提交用例
        driver.findElement(By.id("submit")).click();
        // 提交用例后,增加等待时间,让页面加载完成再判断
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // 定义一个变量,这个变量就是列表中我新建成功的用例xpath对应的位置变量i。
        int deletexpathforint = 0;
        // 把用例标题的xpath参数化,循环取列表里的标题,和新建用例标题判断,来验证新建用例是否成功
        for(int i=1;i<=20;i++){
        String xpath = "//div[@id='datatable-caseList']/div[2]/div[1]/div/table/tbody/tr["+i+"]/td[4]/a";
        // 定义一个string,这是从列表中取得的用例标题
        String titlename = null;
        // 这种情况是 用例不够20条,那么对导致xpath不存在,会出现异常,也说明找不到新建的用例标题,即用例新建不成功
        try{
            titlename = driver.findElement(By.xpath(xpath)).getText();
        }catch(Exception e){
            Assert.assertTrue("找到用例列表最后一条,还是不匹配(不够20条)",false);
        }
        // 找到相同标题的用例,直接assert为成功,并且跳出for循环
        if(titlestr.equals(titlename)){
            Assert.assertTrue(true);
            // 找到用例标题后,把for里的i赋值给变量,用例定位此用例的删除按钮。
            deletexpathforint = i;
            break;
        }
        // 找到最后一条,还是没有找到,那我就直接定义为失败
        if(i==20){
            Assert.assertTrue("找到用例列表最后一条,还是不匹配(够20条)",false);
        }
        }
        
        // 删除新建的用例xpath
        String deletexpath = "//div[@id='datatable-caseList']/div[2]/div[3]/div/table/tbody/tr["+deletexpathforint+"]/td/a[5]/i";
        // 单击删除按钮
        driver.findElement(By.xpath(deletexpath)).click();
        // 弹出alert对话框,获得一个alert对象
        Alert alt = driver.switchTo().alert();
        // 点击alert对话框的“确认”按钮
        alt.accept();

        // 关闭浏览器
        driver.quit();
    }

}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
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 org.openqa.selenium.interactions.Actions;


public class MoveToElement {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        // 设置驱动
        System.setProperty("webdriver.chrome.driver","D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        // 启动浏览器
        WebDriver driver=new ChromeDriver();
        // 访问网易的url
        driver.get("https://www.163.com/");
        // 弹出广告,这个地方就没直接处理广告,而是增加等待时间,使广告结束。
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 轮播图下方的“要闻”的xpath
        String xpathstr = "//*[@id='js_index2017_wrap']/div[2]/div[2]/div[4]/div[1]/div[2]/div/div/ul/li[1]/a";
        // 轮播图下方的“要闻”的元素
        WebElement wb = driver.findElement(By.xpath(xpathstr));
        // 拉动滚动条,使“要闻”显示在视窗中,即轮播图下方的小圆点也显示在视窗中
        if(driver instanceof JavascriptExecutor){
            ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView", wb);    
        }
        // 第四个轮播图的小圆点xpath是
        String fourth = "//div[@class='focus_body' and @ne-role='slide-body' and @ne-swipe='state.onswipe($event)']/../div[2]/span[4]";
        // 第四个轮播图的小圆点元素
        WebElement fourthwb = driver.findElement(By.xpath(fourth));
        // 鼠标移动到轮播图第四张图片的小圆点上
        Actions action = new Actions(driver);
        action.moveToElement(fourthwb).build().perform();
        
        // 轮播图的第四张标题的xpth
        String fourthtitlexpath = "//*[@id='js_index2017_wrap']/div[2]/div[2]/div[4]/div[1]/div[1]/div[1]/div/div[1]/ul/li[4]/div[1]/h3/a";
        // 轮播图的第四张标题的内容
        String fourthtitle = driver.findElement(By.xpath(fourthtitlexpath)).getText();
        // 判断第四张标题是不是预期结果
        Assert.assertEquals("狗把驴咬了驴受惊吓撞坏A8L 修车费10万", fourthtitle);
    }

}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import java.util.Iterator;
import java.util.Set;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class OpenNewWindow {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        // 把浏览器驱动的位置定义到系统中
        System.setProperty("webdriver.chrome.driver", "D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        // new一个浏览器对象
        WebDriver driver = new ChromeDriver();
        // 访问火狐首页
        driver.get("https://home.firefoxchina.cn/");
        // 点击“网易”
        driver.findElement(By.xpath("//a[@href='http://www.163.com/' and @title='网 易']")).click();
        // 取火狐首页的handle
        String firefoxpage = driver.getWindowHandle();
        // 定义字符串变量网易首页的handle
        String neteasepage = null;
        // 取自动化打开所有页的handles,现在已经打开两个页面,分别是火狐首页和网易首页
        Set<String> set = driver.getWindowHandles();
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String temp = it.next();
            if(!temp.equals(firefoxpage)){
                neteasepage = temp;
            }
        }
        System.out.println(neteasepage);
        System.out.println(firefoxpage);
        // 取得火狐首页左上角的logo文字
        String firefoxlogtext=driver.findElement(By.xpath("//a[@href='http://www.firefox.com.cn/?igfox' and @title='火狐官网']")).getText();
        System.out.println(firefoxlogtext);
        Assert.assertEquals("火狐官网", firefoxlogtext);    
        // 切换driver的焦点到网易首页
        driver.switchTo().window(neteasepage);
        // 取得网易首页左上角的logo文字
        String neteaselogtext=driver.findElement(By.xpath("//a[@id='wljd']/../h1/a[@href='http://www.163.com/']")).getText();
        System.out.println(neteaselogtext);
        Assert.assertEquals("网易 有态度", neteaselogtext);
        // 在网易首页点击“新闻”,打开网易新闻首页
        driver.findElement(By.xpath("//a[@href='http://news.163.com/' and @class='fontb']")).click();
       // 打开网易新闻首页,增加一个等待时间
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 定义字符串变量网易新闻首页的handle
         String neteasenewspage = null;
         // 取自动化打开所有页的handles,现在已经打开三个页面,分别是火狐首页,网易首页和网易新闻首页
         Set<String> secondset = driver.getWindowHandles();
         Iterator<String> secondit = secondset.iterator();
         while(secondit.hasNext()){
             String temp = secondit.next();
             if(temp.equals(firefoxpage)||temp.equals(neteasepage)){
                 continue;
             }
             neteasenewspage=temp;
         }
         System.out.println(neteasenewspage);
        
       
    }

}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

package android1708selenium;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ScreenShot {

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {
        System.setProperty("webdriver.chrome.driver", "D:\\software\\win_soft\\selenium\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.baidu.com");
        File srcFile = null;
        if(driver instanceof TakesScreenshot){
            srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        }
        try {
            FileUtils.copyFile(srcFile, new File("\\android1708\\baidu.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("发生意外了,无法截图");
        }
        System.out.println("截图成功");
    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值