×
您的位置: 首页 > 编程笔记

Selenium+java - 下拉框处理

Selenium Java 时间:2019-08-02  查看:220   收藏

常见下拉框也分两种:一种是标准控件和非标准控件(一般为前端开发人员自己封装的下拉框),本篇文章中将重点讲解标准下拉框操作。

1、Select提供了三种选择某一项的方法

  • select.selectByIndex # 通过索引定位

  • selectByValue         # 通过value值定位

  • selectByVisibleText   # 通过可见文本值定位

使用说明:

  • index索引是从“0”开始;

  • value是option标签中value属性值定位;

  • VisibleText是在option是显示在下拉框的文本;

2、Select提供了三种返回options信息的方法

  • getOptions() # 返回select元素所有的options

  • getAllSelectedOptions()    # 返回select元素中所有已选中的选项

  • getFirstSelectedOption()   # 返回select元素中选中的第一个选项

3、Select提供了四种取消选中项的方法

  • select.deselectAll() # 取消全部的已选择项

  • deselectByIndex()        # 取消已选中的索引项

  • deselectByValue()        # 取消已选中的value值

  • deselectByVisibleText()  # 取消已选中的文本值

4、被测页面代码

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Select控件练习案例</title></head><body><h4>请选择你的英雄:</h4><select id="select"><option value="1">李白</option><option selected="selected" value="2">韩信</option><option value="3">典韦</option><option value="4">凯</option></select></body></html>

具体示例代码如下:

package com.brower.demo;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.support.ui.Select;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test;import java.util.concurrent.TimeUnit;public class TestSelectDemo {

    WebDriver driver;

    @BeforeClasspublic void beforeClass() {
        System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
        driver = new ChromeDriver();
    }

    @Testpublic void testSelectDemo() {//打开测试页面driver.get("file:///C:/Users/Administrator/Desktop/SelectDemo.html");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//获取select元素对象WebElement element = driver.findElement(By.id("select"));
        Select select = new Select(element);//根据索引选择,选择第1个英雄:李白select.selectByIndex(0);//根据value值选择第4个英雄:凯select.selectByValue("4");//根据文本值选择第2个英雄:韩信select.selectByVisibleText("韩信");//判断是否支持多选        System.out.println(select.isMultiple());

    }

    @AfterClasspublic void afterClass() {
        driver.quit();
    }
}

以上便是关于select控件处理的演示案例,具体实践还需要结合实际的工作需要来进行。

 

0% (0)
0% (0)