使用Selenium自动化测试web程序

 

Selenium 是目前用的最广泛的Web UI 自动化测试框架,核心功能就是可以在多个浏览器上进行自动化测试。
支持多平台:windows、linux、MAC ,支持多浏览器:ie、ff、safari、opera、chrome,多语言C、 java、ruby、python...
Selenium IDE是firefox浏览器的一个插件。提供简单的脚本录制、编辑与回放功能。Selenium Grid是用来对测试脚步做分布式处理。现在已经集成到selenium server 中了。

依赖:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

例子1:表单填充

        // 如果不设置将搜索环境变量
        System.setProperty("webdriver.chrome.driver", "C:\\MyDrivers\\selenium\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.get("http://www.baidu.com/");
        // 最大化窗口
        driver.manage().window().maximize();
        // 定制大小窗口
        //driver.manage().window().setSize(new Dimension(480, 800));
        Thread.sleep(1000);
    //提交表单(搜索字符)
        WebElement searchBox = driver.findElement(By.id("kw"));
        searchBox.sendKeys("ChromeDriver");
        searchBox.submit();
        Thread.sleep(3000);
    //退出
    driver.quit();

 

例子2:元素定位

        //8种定位方式在Python selenium中所对应的方法为:
        findElement(By.id())
        findElement(By.name())
        findElement(By.className())
        findElement(By.tagName())
        findElement(By.linkText())
        findElement(By.partialLinkText())
        findElement(By.xpath())
        findElement(By.cssSelector())


例子3:点击链接、后退、刷新浏览器

//        //点击链接
//        driver.findElement(By.linkText("新闻")).click();
//        System.out.printf("now accesss %s \n", driver.getCurrentUrl());
//        Thread.sleep(2000);

//        //执行浏览器后退
//        driver.navigate().back();
//        System.out.printf("back to %s \n", driver.getCurrentUrl());
//        Thread.sleep(2000);

//        //刷新页面
//        driver.navigate().refresh();

例子4:鼠标、键盘事件

// 鼠标右键点击指定的元素
        action.contextClick(driver.findElement(By.id("element"))).perform();

// 鼠标右键点击指定的元素
        action.doubleClick(driver.findElement(By.id("element"))).perform();

// 鼠标拖拽动作, 将 source 元素拖放到 target 元素的位置。
        WebElement source = driver.findElement(By.name("element"));
        WebElement target = driver.findElement(By.name("element"));
        action.dragAndDrop(source,target).perform();

// 释放鼠标
        action.release().perform();

        WebElement input = driver.findElement(By.id("kw"));

        //输入框输入内容
        input.sendKeys("seleniumm");
        Thread.sleep(2000);

        //删除多输入的一个 m
        input.sendKeys(Keys.BACK_SPACE);
        Thread.sleep(2000);

        //输入空格键+“教程”
        input.sendKeys(Keys.SPACE);
        input.sendKeys("教程");
        Thread.sleep(2000);

        //ctrl+a 全选输入框内容
        input.sendKeys(Keys.CONTROL,"a");
        Thread.sleep(2000);

        //ctrl+x 剪切输入框内容
        input.sendKeys(Keys.CONTROL,"x");
        Thread.sleep(2000);

        //ctrl+v 粘贴内容到输入框
        input.sendKeys(Keys.CONTROL,"v");
        Thread.sleep(2000);

        //通过回车键盘来代替点击操作
        input.sendKeys(Keys.ENTER);
        Thread.sleep(2000);

例子5:Xpath定位

        WebElement search = driver.findElement(By.id("kw"));
        search.sendKeys("Selenium");
        search.sendKeys(Keys.ENTER);
        Thread.sleep(2000);

        System.out.println("Search after================");

        //获取当前的 title 和 url
        System.out.printf("title of current page is %s\n", driver.getTitle());
        System.out.printf("url of current page is %s\n", driver.getCurrentUrl());

        //获取第一条搜索结果的标题
        WebElement result = driver.findElement(By.xpath("//div[@id='content_left']/div/h3/a"));
        System.out.println(result.getText());

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


例子6:定位元素组

        //定位元素组
        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());
        }
        //打印第n结果的标题
        WebElement text = search_result.get(search_result.size() - 10);
        System.out.println(text.getText());

例子7:Javascript事件

     // 将页面滚动条拖到底部
    ((JavascriptExecutor)driver).executeScript("window.scrollTo(100,450);");
    Thread.sleep(3000);

例子8:下拉框交互、弹窗交互

    driver.findElement(By.linkText("设置")).click();
        driver.findElement(By.linkText("搜索设置")).click();
        Thread.sleep(2000);

        //<select>标签的下拉框选择
        WebElement el = driver.findElement(By.xpath("//select"));
        Select sel = new Select(el);
        sel.selectByValue("20");//选第2个
        Thread.sleep(2000);

        //保存设置
        driver.findElement(By.className("prefpanelgo")).click();

        //接收弹窗
        driver.switchTo().alert().accept();
        Thread.sleep(2000);

例子9:文件上传

        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(srcFile,new File("d:\\screenshot.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }


例10:自动登陆测试

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class LoginUsingSelenium {

    @Test
    public void login() {
        // TODO Auto-generated method stub
        
        System.setProperty("webdriver.chrome.driver", "path of driver");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.linkedin.com/login");
        
        WebElement username=driver.findElement(By.id("username"));
        WebElement password=driver.findElement(By.id("password"));
        WebElement login=driver.findElement(By.xpath("//button[text()='Sign in']"));
        
        username.sendKeys("example@gmail.com");
        password.sendKeys("password");
        login.click();
        
        String actualUrl="https://www.linkedin.com/feed/";
        String expectedUrl= driver.getCurrentUrl();
        
        Assert.assertEquals(expectedUrl,actualUrl);
        
        
    }

}

 

最后有个不错的云测试平台,可以实时测试和自动化测试,可以测试2000+桌面或移动端浏览器。
https://www.lambdatest.com/selenium-automation
如果是这个云端的测试,代码改写如下

import java.net.URL;
import java.util.concurrent.TimeUnit;

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.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LoginUsingSelenium {


    public RemoteWebDriver driver = null;
    public String url = "https://www.lambdatest.com/";
    public static final String  username= "sadhvisingh24";
    public static final String auth_key = "auth key generated";
    public static final String URL = "@hub.lambdatest.com/wd/hub";
    boolean status = false;


    @Test
    public void login () {
        // TODO Auto-generated method stub
        try {

            driver.manage().window().maximize();
            driver.get("https://www.linkedin.com/login");

            WebElement username = driver.findElement(By.id("username"));
            WebElement password = driver.findElement(By.id("password"));
            WebElement login = driver.findElement(By.xpath("//button[text()='Sign in']"));

            username.sendKeys("linkedin username");
            password.sendKeys("fake password");
            login.click();

            String actualUrl = "https://www.linkedin.com/feed/";
            String expectedUrl = driver.getCurrentUrl();

            if (actualUrl.equalsIgnoreCase(expectedUrl)) {
                System.out.println("Test passed");
                status = true; //Lambda status will be reflected as passed
              } else {
                System.out.println("Test failed"); //Lambda status will be reflected as passed

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        finally {
            tearDown();
        }


    }



    @BeforeClass
    public void setUp() {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("browserName", "chrome");
        capabilities.setCapability("version", "72.0");
        capabilities.setCapability("platform", "win8"); // If this cap isn't specified, it will just get the any available one
        capabilities.setCapability("build", "TestNG_login_1");
        capabilities.setCapability("name", "TestNG_login_1");
        capabilities.setCapability("network", true); // To enable network logs
        capabilities.setCapability("visual", true); // To enable step by step screenshot
        capabilities.setCapability("video", true); // To enable video recording
        capabilities.setCapability("console", true); // To capture console logs
        try {

            driver = new RemoteWebDriver(new URL("https://" + username + ":" + auth_key + URL), capabilities);

        } catch (Exception e) {

            System.out.println("Invalid grid URL" + e.getMessage());
        }

    }
    private void tearDown () {
        if (driver != null) {
            ((JavascriptExecutor) driver).executeScript("lambda-status=" + status); //Lambda status will be reflected as either passed/ failed

            driver.quit();

            System.out.println("The setup process is completed");

        }
    }
}

 

posted @ 2020-04-08 10:28  昕友软件开发  阅读(484)  评论(0编辑  收藏  举报
欢迎访问我的开源项目:xyIM企业即时通讯