使用Selenium webdriver检查和取消选中复选框。
我正在使用页面对象模式,所以我的代码就是这样出现的。
SelectCheckBox("Check"); OR SelectCheckBox("Uncheck");
[FindsBy(How = How.Id, Using = "payment_sameasdeliveryaddress")]
public IWebElement checkbox_Address = null;
public void SetCheckBox(string value)
{
//Console.Write("checkbox state : " + checkbox_Address.Selected);
if (value.ToLower().Equals("uncheck") && checkbox_Address.Selected )
{
checkbox_Address.Click();
}
else if (value.ToLower().Equals("check") && !checkbox_Address.Selected)
{
checkbox_Address.Click();
}
答案 0 :(得分:1)
自从我编写任何.NET以来已经有好几年了,所以下面甚至可能都没有编译!但希望你明白了。
// the individual elements should be declared private
private IWebElement payment_sameasdeliveryaddress;
// if you name it same as the source element ID, PageFactory will find it for you
// flag = true, means you want it checked
public void SelectCheckBox(Boolean check)
{
if (!check && payment_sameasdeliveryaddress.Selected) {
payment_sameasdeliveryaddress.Click();
}
else if (check && !payment_sameasdeliveryaddress.Selected) {
payment_sameasdeliveryaddress.Click();
}
答案 1 :(得分:0)
这不也可以吗?
// flag = true, means you want it checked
public void SelectCheckBox(Boolean check)
{
if (check ^ payment_sameasdeliveryaddress.Selected) {
payment_sameasdeliveryaddress.Click();
}
}
答案 2 :(得分:0)
使用selenium webdriver 3.9.1和testng 6.14分享刚刚在当前项目中实现的代码段
//根据是否选中复选框返回布尔值 Boolean chkBx1Sel = driver.findElement(By.xpath(elementXpath))。isSelected();
案例1:选中复选框
if(dataValofChkBx != null && dataValofChkBx.equalsIgnoreCase("Y"))
{
if(chkBx1Sel.toString() == "false") //i.e., checkbox is not already checked
{
driver.findElement(By.xpath(POP2GUIConstants.ggsnFwlfUpdChkBx)).click();
}
}
=============================================== =================================
案例2:取消选中复选框
if(dataValofChkBx != null && dataValofChkBx.equalsIgnoreCase("N"))
{
if(chkBx1Sel.toString() == "true") //i.e., checkbox is already checked
{
driver.findElement(By.xpath(POP2GUIConstants.ggsnFwlfUpdChkBx)).click();
}
}
答案 3 :(得分:0)
通过将isSelected()方法与元素一起使用来检查是否选中复选框的最简单方法。例如:
if(getCheckBox().isSelected()){
getCheckBox.click();
}
public WebElement getCheckBox(){
return driver.findElement(termsCheck);
}