我无法根据其现有状态自动执行切换按钮

时间:2018-09-05 15:17:58

标签: selenium-webdriver toggle ui-automation

就我而言,我想先检查一下切换按钮的开/关状态。如果关闭,则我想将其打开;如果已经打开,则应保持打开状态。我已经使用过isSelected,isEnabled和isDisplayed,但是此方法都不讨厌按钮的状态。

**Following is my trial code:**

if(driver.findElement(By.xpath("(//span[@class='toggle-handle btn btn-default'])[2]")).isSelected()) {
System.out.println("is turned on");
}
else {
driver.findElement(By.xpath("(//div[@class='feed-toggle-container brand-integrity-site-visibility'])[2]")).click();
}

HTML:

<tr>
    <td>Atlas Copco Brand Integrity Site</td>
    <td>ac.website.com</td>
    <td>
        <div class="feed-toggle-container brand-integrity-site-visibility">
            <div class="toggle btn btn-default off" data-toggle="toggle" style="width: 73px; height: 32px;">
                <input class="feed-toggle" data-url="https://admin.stage.cwsplatform.com/api/brand-integrity-site/7" data-toggle="toggle" data-onstyle="success" name="visible_to_dealer" type="checkbox" value="1">
                <div class="toggle-group">
                    <label class="btn btn-success toggle-on">On</label>
                    <label class="btn btn-default active toggle-off">Off</label><span class="toggle-handle btn btn-default"></span>
                </div>
            </div>
        </div>
    </td>
    <td>
        <a target="_blank" href="http://ac.website.com.live.stage.cwsplatform.com/cws-login">
            <button class="btn btn-primary">Manage Content</button>
        </a>
    </td>
    <td>
        <a target="_blank" href="http://ac.website.com.demo.stage.cwsplatform.com/cws-login">
            <button class="btn btn-default">Manage Content</button>
        </a>
    </td>
</tr>

切换容器品牌完整性站点可见性。单击此类基本上可以打开和关闭按钮。如果打开,则将其关闭,反之亦然。使用上面的代码只是关闭了On状态,而不仅仅是将其保持为on状态。

打开按钮时为HTML:

<label class="btn btn-success toggle-on">On</label>

按钮关闭时为HTML:

<label class="btn btn-default active toggle-off">Off</label>

1 个答案:

答案 0 :(得分:0)

您可以针对以下情况执行以下操作:

  • 您需要先检查其当前状态
  • 您可以根据课程价值进行检查
  • 获取类值后,您可以检查并验证其状态
  • 因此您可以处理用户定义的操作

//This is to Locate on label
By locateOnLabel = By.xpath("//div[@class='toggle-group']//label[contains(text(),'On')]");


//This is to Locate off label    
By locateOffLabel = By.xpath("//div[@class='toggle-group']//label[contains(text(),'Off')]");

//Retrieve their class, it given identification whether its On/Off
String getLabelONClass = driver.findElement(locateOnLabel).getAttribute("class");
String getLabelOFFClass = driver.findElement(locateOffLabel).getAttribute("class");

//compare class values, and Perform actions
if(getLabelOFFClass.equals("btn btn-default active toggle-off)) {      
       Click that Webelement if you want to turn on 
}
   else if (getLabelONClass.equals("btn btn-success toggle-on")) {                   
       You can notify message, That Button is already ON
  }