Selenium+java - 下拉框处理

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

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

  • select.selectByIndex # 经过索引定位
  • selectByValue # 经过value值定位
  • selectByVisibleText # 经过可见文本值定位

使用说明:

  • index索引是从“0”开始;
  • value是option标签中value属性值定位;
  • VisibleText是在option是显示在下拉框的文本;

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

  • getOptions() # 返回select元素全部的options
  • getAllSelectedOptions() # 返回select元素中全部已选中的选项
  • getFirstSelectedOption() # 返回select元素中选中的第一个选项

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

  • select.deselectAll() # 取消所有的已选择项
  • deselectByIndex() # 取消已选中的索引项
  • deselectByValue() # 取消已选中的value值
  • deselectByVisibleText() # 取消已选中的文本值

四、被测页面代码

<!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控件处理的演示案例,具体实践还须要结合实际的工做须要来进行。java

原文出处:https://www.cnblogs.com/longronglang/p/11285956.htmlweb

相关文章
相关标签/搜索