selenium-webdriver - 我无法根据其现有状态自动切换按钮
问题描述
在我的情况下,我想首先检查切换按钮是否打开/关闭。如果它关闭,那么我想打开它,如果它已经打开,那么它应该保持打开。我使用过 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>
feed-toggle-container 品牌完整性站点可见性。点击这个类基本上可以打开和关闭按钮。如果它打开,它将关闭它,反之亦然。使用上面的代码只是关闭 On 状态,而不是让它保持在 on 状态。
按钮打开时的 HTML:
<label class="btn btn-success toggle-on">On</label>
按钮关闭时的 HTML:
<label class="btn btn-default active toggle-off">Off</label>
解决方案
您可以执行以下相同的场景:
- 您需要首先检查其当前状态
- 您可以根据类值进行检查
- 获取类值后,可以检查和验证它的状态
- 因此您可以处理用户定义的操作
//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
}
推荐阅读
- reactjs - 如何引起对重新渲染复选框的反应
- swift - 在 SwiftUI 中单击按钮时创建重复计数器
- ruby-on-rails - 为什么 http 域重定向而不是 https 域?
- python - 我可以看到两个日期之间的文件,但我也需要将它们复制并合并到另一个文件夹
- javascript - moment-timezone :从一个时区转换到另一个时区时没有得到想要的时间
- mongodb - Amazon Document DB 中的 Mongodb 聚合函数
- go - 在函数内设置空接口{}类型的变量的值
- ios - 为什么我们不能在 swiftUI Priview 中传递实例变量?
- python - 我想创建一个简单的太空游戏,但每次我想拍摄外星人,但我总是得到 ValueError: list.remove(x): x not in list
- javascript - 使用javascript计算与数字对应的颜色