原文:http://www.cnblogs.com/tobecrazy/p/4570494.html

今天,总结一下selenium怎么操作web页面常见的元素。

主要有:

  • 上传
  • alter dialog
  • prompt dialog
  • confirm dialog
  • select list
  • radio box
  • input box
  • checkBox

测试页面如下:

 

selenium 最核心的技巧是WebElement的识别和定位

selenium总共有八种定位方法 

  1. By.id()  通过id定位
  2. By.name()  通过name 定位
  3. By.xpath() 通过xpath定位
  4. By.className() 通过className定位
  5. By.cssSelector() 通过CSS 定位
  6. By.linkText() 通过linkText
  7. By.tagName() 通过tagName
  8. By.partialLinkText() 通过匹到的部分linkText

目前,使用比较多的是cssSelector和xpath,因为一个页面中Id name className tagName LinkText等比较容易重复 不容易 确定唯一

接下来会有具体的例子来演示如何定位 


上传文件

一般,上传页面如果是input,像这样的,可以使用sendkeys

首先,这里使用xpath定位到该元素,然后使用sendKeys即可,sendKeys send你要上传的文件的绝对路径

1 //td/input[@type='file']

也可以使用cssSelector,关于xpath和cssSelector更多知识,以后会做一些专题

1 td>input[type='file']

如何验证你写的xptah/cssSelector是正确的呢?

有以下几种方法:

  • F12 ,使用浏览器的console  ,xpath使用$x()  function,css使用    $() function                                                          
  • 使用第三方插件firebug
  • 使用selenium IDE

alert对话框

 细分三种,Alert,prompt,confirm

 Selenium有以下方法:

     

 Alert alert =driver.switchTo().alert();

1. driver.switchTo().alert();  获取alert

2. alert.accept(); 点确定

3. alert.dismiss(); 点取消

4. alert.getText();获取alert的内容

 

    


select菜单

    select也是比较常见的,selenium封装了以下方法

创建select

WebElement selector = driver.findElement(By.id("Selector"));
Select select = new Select(selector);

选择select的option有以下三种方法

  • selectByIndex(int index) 通过index
  • selectByVisibleText(String text) 通过匹配到的可见字符
  • selectByValue(String value) 通过匹配到标签里的value
WebElement selector = driver.findElement(By.id("Selector"));
        Select select = new Select(selector);
        select.selectByIndex(3);
        select.selectByVisibleText("桃子");
        select.selectByValue("apple");

输入框

输入框就比较简单了,不再多说

sendKeys()输入内容

clear()  清空


单选框(RadioBox)

单选框可以有获取状态,是否被选中

radioBox.isSelected();

是否enable

radioBox.isEnabled()

使用click方法选中


复选框(checkBox)

复选框和单选框基本差不多,此处略


超链接

超链接比较常见,一般都是标签a

<a href="http://www.cnblogs.com/tobecrazy/" >Copyright 2015 to be crazy </a>

一般使用click方法

这里我们了解一下浏览器打开超链接时,如果是chrome,点超链接的同时按下Ctrl会打开新标签,按下shift会打开新窗口

这里单讲一下不同窗口切换.

selenium有两个关于获取窗口的方法:

1. driver.getWindowHandle();  返回的是字符串,获取当前窗口的句柄

2. driver.getWindowHandles(); 返回的是 Set<String> ,获取所有窗口

如果你想在窗口之间切换

driver.switchTo().window(window);

小技巧: 如何滚动到你定位的元素

这里使用java script

// scroll to mylink
        JavascriptExecutor scroll = (JavascriptExecutor) driver;
        scroll.executeScript("arguments[0].scrollIntoView();", myLink);

接下来是所有测试代码:

package com.packt.webdriver.chapter1;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;

import com.packt.webdriver.chapter3.DriverFactory;

/**
 * this method is for deal with base web elements
 *
 * @author Young
 *
 */
public class dealWithElements {

    public static void main(String[] args) throws Exception {
        String URL = "file://demo.html";
        String chromdriver="E:\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", chromdriver);
        ChromeOptions options = new ChromeOptions();
//        options.addExtensions(new File(""));
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability("chrome.switches",
                Arrays.asList("--start-maximized"));
        options.addArguments("--test-type", "--start-maximized");
        WebDriver driver=new ChromeDriver(options);

        driver.get(URL);
        // max size the browser
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

        WebElement upload = driver.findElement(By
                .xpath("//td/input[@type='file']"));
        upload.sendKeys("C:/Users/Young/Desktop/demo.html");
        Assert.assertTrue(upload.getAttribute("value").contains("demo"));
        // for alert
        WebElement clickOnAlert = driver.findElement(By
                .xpath("//td/input[@name='alterbutton']"));
        clickOnAlert.click();
        delay(2);
        // get alert
        Alert alert = driver.switchTo().alert();
        Assert.assertTrue(alert.getText().contains("alert"));
        // click alert ok
        alert.accept();

        delay(2);
        // for prompt
        WebElement clickOnPrompt = driver.findElement(By
                .xpath("//td/input[@name='promptbutton']"));
        clickOnPrompt.click();
        delay(2);
        Alert prompt = driver.switchTo().alert();

        prompt.sendKeys("I love Selenium");
        prompt.accept();
        delay(5);
        Alert afterAccept = driver.switchTo().alert();
        Assert.assertTrue(afterAccept.getText().contains("I love Selenium"));
        // click alert ok
        afterAccept.accept();
        delay(2);
        // for confirm
        WebElement clickOnConfirm = driver.findElement(By
                .xpath("//td/input[@name='confirmbutton']"));
        clickOnConfirm.click();
        delay(2);
        Alert confirm = driver.switchTo().alert();
        confirm.dismiss();
        delay(2);
        Alert afterDismiss = driver.switchTo().alert();
        Assert.assertTrue(afterDismiss.getText().contains("You pressed Cancel"));
        delay(2);
        afterDismiss.accept();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

        WebElement selector = driver.findElement(By.id("Selector"));
        Select select = new Select(selector);
        select.selectByIndex(3);
        select.selectByVisibleText("桃子");
        select.selectByValue("apple");

        System.out.println(select.getAllSelectedOptions().toString());
        delay(2);
        WebElement showSelectResult = driver.findElement(By
                .name("showSelectResult"));
        showSelectResult.click();
        delay(2);
        Alert yourSelect = driver.switchTo().alert();
        Assert.assertTrue(yourSelect.getText().contains("苹果"));

        delay(2);
        yourSelect.accept();

        // input box
        WebElement editBox = driver.findElement(By
                .xpath("//td/input[@id='edit']"));
        editBox.sendKeys("Selenium is good");
        WebElement submitButton = driver.findElement(By
                .xpath("//input[@type='button' and @name='submit']"));
        submitButton.click();
        delay(2);
        Alert submitAlert = driver.switchTo().alert();
        Assert.assertEquals(submitAlert.getText(), "Selenium is good");
        submitAlert.accept();
        delay(2);

        // for radio Box

        WebElement duRadioBox = driver.findElement(By
                .cssSelector("div#radio>input.Baidu"));
        WebElement aLiRadioBox = driver.findElement(By
                .cssSelector("div#radio>input.Alibaba"));
        WebElement TXRadioBox = driver.findElement(By
                .cssSelector("div#radio>input.Tencent"));
        WebElement MiRadioBox = driver.findElement(By
                .cssSelector("div#radio>input.Mi"));
        delay(2);
        Assert.assertTrue(TXRadioBox.isSelected());
        Assert.assertTrue(!MiRadioBox.isEnabled());
        delay(2);
        duRadioBox.click();
        Assert.assertTrue(duRadioBox.isSelected());
        delay(2);

        aLiRadioBox.click();
        Assert.assertTrue(aLiRadioBox.isSelected());
        delay(2);

        // for checkBox

        List<WebElement> webCheckBox = driver.findElements(By
                .xpath("//input[@type='checkbox']"));

        for (WebElement e : webCheckBox) {
            e.click();
            Assert.assertTrue(e.isSelected());
            delay(2);
        }

        // for links
        String defaultWindow = driver.getWindowHandle();
        WebElement myLink = driver.findElement(By
                .linkText("Copyright 2015 to be crazy"));
        delay(3);
        // scroll to mylink
        JavascriptExecutor scroll = (JavascriptExecutor) driver;
        scroll.executeScript("arguments[0].scrollIntoView();", myLink);
        // open link in a new windows press shift when you click
        delay(2);
        Actions actions = new Actions(driver);
        actions.keyDown(Keys.SHIFT).click(myLink).perform();

        delay(3);
        Set<String> currentWindows = driver.getWindowHandles();
        System.out.println(currentWindows.size());
        for (String window : currentWindows) {
            if (!window.endsWith(defaultWindow)) {
                driver = driver.switchTo().window(window);
                driver.manage().timeouts()
                        .pageLoadTimeout(60, TimeUnit.SECONDS);
                driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                break;
            }
        }

        Assert.assertTrue(driver.getCurrentUrl().contains("tobecrazy"));
        delay(10);

        driver.quit();
    }

    /**
     * @author Young
     * @param seconds
     */
    public static void delay(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

selenium总结篇,常见方法和页面元素的操作【转】的更多相关文章

  1. selenium 总结篇,常见方法和页面元素的操作

    今天,总结一下selenium怎么操作web页面常见的元素. 主要有: 上传 alter dialog prompt dialog confirm dialog select list radio b ...

  2. 爬虫 selenium+Xpath 爬取动态js页面元素内容

    介绍 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如 ...

  3. Python3 Selenium自动化web测试 ==> 第二节 页面元素的定位方法 <上>

    前置步骤: 上一篇的Python单元测试框架unittest,我认为相当于功能测试测试用例设计中的用例模板,在自动化用例的设计过程中,可以封装一个模板,在新建用例的时候,把需要测试的步骤添加上去即可: ...

  4. Python3 Selenium自动化web测试 ==> 第二节 页面元素的定位方法 -- iframe专题 <下>

    学习目的: 掌握iframe矿建的定位,因为前端的iframe框架页面元素信息,大多时候都会带有动态ID,无法重复定位. 场景: 1. iframe切换 查看iframe 切换iframe 多个ifr ...

  5. Selenium(二十):expected_conditions判断页面元素

    1. 判断元素(expected_conditons) 作为一个刚刚转到python开发的小朋友,在开发前只将前辈们封装的方法看了一遍,学了一边selenium基础.看到封装的方法有什么判断元素是否存 ...

  6. [Selenium]通过JavaScript来对隐藏的元素执行操作

    对不可见元素进行操作时,如果通过普通的方式不可行,可以尝试用Javascript Scroll hidden element into view ((JavascriptExecutor) drive ...

  7. selenium采用xpath方法识别页面元素

    有些HTML页面中的元素中属性较少,经常有找不到id.class.name等常用属性的时候,这个时候xpath.css就能很好的识别到我们的元素. Firefox和chrome浏览器中均有xpath. ...

  8. selenium采用find_element_by方法识别页面元素

    主要是练习获取页面中的各元素,马克 # coding:utf-8 import time from selenium import webdriver import unittest from pyt ...

  9. Python+Selenium练习篇之17-断言页面标题

    继续来介绍一个Selenium中页面title断言方法. 相关脚本代码如下: # coding=utf-8 import time from selenium import webdriver dri ...

随机推荐

  1. Nginx的启动、停止与重启

      启动 启动代码格式:nginx安装目录地址 -c nginx配置文件地址 例如: [root@LinuxServer sbin]# /usr/local/nginx/sbin/nginx -c / ...

  2. linux服务器加硬盘扩容

    from: http://bbs.chinaunix.net/thread-3613556-1-1.html 试验环境: vmware下,centos6,64位版本,原来系统默认分区,/dev/sda ...

  3. LINQ to XML 编程基础

    1.LINQ to XML类 以下的代码演示了如何使用LINQ to XML来快速创建一个xml: 隐藏行号 复制代码 ?创建 XML public static void CreateDocumen ...

  4. FusionCharts制作报表使用XML导入数据时出现的中文乱码问题

    今天在使用FusionCharts制作报表时用XML导入数据,总是出现乱码问题,下面是我的解决方案. 让FusionCharts支持中文 刚刚将XML导入到html中后,在火狐浏览器一直报Invali ...

  5. Android多线程编程之AsyncTask

    进程?线程? 进程是并发执行的程序在执行过程中分配和管理资源的基本单位,是一个动态的概念.每个进程都有自己的地址空间(进程空间).进程空间的大小与处理机位数有关.进程至少有5种基本状态:初始态,执行态 ...

  6. 开源PLM软件Aras详解六 角色与用户以及权限

    在Aras中,角色(Identity),用户(Users),权限(Permissions),分别为3个ItemType,Permissions依赖与Identity,Identity可依赖与User. ...

  7. 【转】Linux学习之路--启动VNC服务

    我的Linux是Fedora 13,安装方法如下: 1.打开终端,执行 # yum install -y tigervnc tigervnc-server 2.编辑/etc/sysconfi/vncs ...

  8. MySQL高级查询语句

    高级查询: 一:多表连接 1.select Info.Code,Info.Name,Nation.Name from Info,Nation where Info.Nation = Nation.Co ...

  9. nginx php-fpm安装配置

    nginx本身不能处理PHP,它只是个web服务器,当接收到请求后,如果是php请求,则发给php解释器处理,并把结果返回给客户端. nginx一般是把请求发fastcgi管理进程处理,fascgi管 ...

  10. C++ STL 助记1:vector

    vector<, ); // Creates vector of 10 ints with value 100 vector<, "hello"); vector< ...