常见下拉框也分两种:一种是标准控件和非标准控件(一般为前端开发人员自己封装的下拉框),本篇文章中将重点讲解标准下拉框操作。
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; @BeforeClass public void beforeClass() { System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); driver = new ChromeDriver(); } @Test public 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()); } @AfterClass public void afterClass() { driver.quit(); } }
以上便是关于select控件处理的演示案例,具体实践还需要结合实际的工作需要来进行。