java【selenium】操作多选元素框

本文介绍使用Selenium WebDriver进行单选框、复选框及下拉列表等Web控件的操作方法,包括如何选择和取消选择选项,并展示了通过不同方式(如值、索引和文本)来操作控件的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import static org.junit.jupiter.api.Assertions.*;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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;

class RadioButtonsAndcheckboxes {
/*
* 单选框和复选框操作
*/
//引入Webdriver
WebDriver driver;
//访问网址
String baseurl;

@BeforeEach
void setUp() throws Exception {
	//谷歌浏览器本地驱动
	System.setProperty("webdriver.chrome.driver", "/Users/lisen/webselenium/selenium/chromedriver");
	//初始化谷歌浏览器
	driver=new ChromeDriver();
	baseurl="file:///Users/lisen/Downloads/PracticePage.html";
	//设置隐性等待
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	//窗口最大化
	driver.manage().window().maximize();
	
	

}

@Test
void test() throws Exception {
	//访问网址
	driver.get(baseurl);
	//打印log
	System.out.println("打开网址完成");
	//查找多选元素列表框
	WebElement element =driver.findElement(By.id("multiple-select-example"));
	//查找Select属性的控件
	Select sel = new Select(element);
	//等待3秒
	Thread.sleep(3000);
	//用Value选中控件元素
	sel.selectByValue("orange");
	//用Value取消选中元素
	sel.deselectByValue("orange");
	//用角标选中控件元素
	sel.selectByIndex(2);
	//用角标取消选中控件元素
	sel.deselectByIndex(2);getClass();
	//用文本选中控件元素
	sel.selectByVisibleText("苹果");
	//用文本取消选中控件元素
	sel.deselectByVisibleText("苹果");
	//打印所有选中的选项
	List<WebElement> selectopions=sel.getAllSelectedOptions();
	for (WebElement option:selectopions) {
		//文本返回所有的选中元素
		System.out.println("打印所有元素"+option.getText());
		
	}
	
	//等待2秒钟
	Thread.sleep(2000);
	//取消所有选中按钮
	sel.deselectAll();
	
	
	
	
}

@AfterEach
void tearDown() throws Exception {
	//等待3秒
	Thread.sleep(3000);
	//关闭浏览器
	driver.quit();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值