被测试的HTML网页:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>下拉框</title>
</head>
<body>
<select name="fruit" size=6 multiple=true>
<option id="peach" value="taozi">桃子</option>
<option id="watermelon" value="xigua">西瓜</option>
<option id="orange" value="juzi">橘子</option>
<option id="kiwifruit" value="mihoutao">猕猴桃</option>
<option id="matbush" value="shanzha">山楂</option>
<option id="litchi" value="lizhi">荔枝</option>
</select>
</body>
</html>
-
通过索引值取消选中某个选项
dropList.deselectByIndex(3);
-
通过value属性值取消选中某个选项
dropList.deselectByValue("shanzha");
-
通过选项的文字,来取消选中某个选项
dropList.deselectByVisibleText("荔枝");
-
取消选中所有选项
dropList.deselectAll();
完整代码:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.Assert;
public class MultipleSelectedOptions {
WebDriver driver;
String baseUrl;
@BeforeMethod
public void setUp() throws Exception {
baseUrl = "E:\\Coding\\JavaCode\\WebAutomationTest\\HTML\\MultipleSelected.html";
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void selectMultipleOptions() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
//使用name属性找到页面上name属性为"fruit"的下拉列表元素
Select dropList = new Select(driver.findElement(By.name("fruit")));
//isMultiple表示判断此下拉菜单列表是否允许多选,多选返回true,单选返回false
Assert.assertTrue(dropList.isMultiple());
//使用选择项索引选择"猕猴桃"选项
dropList.selectByIndex(3);
Thread.sleep(1000);
//使用选项value属性值选中"山楂"选项
dropList.selectByValue("shanzha");
Thread.sleep(1000);
//使用选项文字选中"荔枝"选项
dropList.selectByVisibleText("荔枝");
Thread.sleep(1000);
//deselectAll方法表示取消选择所有选项的选中状态
dropList.deselectAll();
Thread.sleep(1000);
//再次选中这三个选项
dropList.selectByIndex(3);
dropList.selectByValue("shanzha");
dropList.selectByVisibleText("荔枝");
Thread.sleep(1000);
//deselectByIndex方法表示取消索引为3的选项的选中状态
dropList.deselectByIndex(3);
Thread.sleep(1000);
//deselectByValue方法表示取消value属性值为"shanzha"的选项的选中状态
dropList.deselectByValue("shanzha");
Thread.sleep(1000);
//deselectByVisibleText方法表示取消文字为"荔枝"的选项的选中状态
dropList.deselectByVisibleText("荔枝");
Thread.sleep(1000);
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}