我想要一个切换开关,具体取决于开关状态。
如果是" span.switch-right"我想这样做:
findElement(By.cssSelector("span.switch-left")).click();
如果是" span.switch-left"我想这样做:
findElement(By.cssSelector("span.switch-right")).click();
HTML:
<div tabindex="0" class="has-switch switch-on switch-animate">
<div>
<span class="switch-left">ON</span>
<label for="profile_isProfileSharedWithNearby"> </label>
<span class="switch-right">OFF</span>
<input id="profile_isProfileSharedWithNearby" name="profile[isProfileSharedWithNearby]" class="form-control-borderless hide" value="1" checked="checked" type="checkbox">
</div>
</div>
答案 0 :(得分:3)
假设文本可靠,您可以使用xpath选择器:
findElement(By.xpath("//span[contains(@class, 'switch-') and contains(text(), 'OFF')]")).click();
这将始终点击OFF
开关。
答案 1 :(得分:2)
您可能想尝试Fluent Wait
。它使您能够等待一个元素绕过某些异常类型并在一段时间后轮询DOM
,并确保它是否存在。
By by = By.cssSelector("span.switch-left");
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(by);
}
});
foo.click();
取自here
修改强> 在混淆(;-))讨论后提供解决方案
//*[@tabindex='0'][contains(@class,'switch-off')]
答案 2 :(得分:1)
您可以通过以下代码检查开关状态,并可以将其关闭
List<WebElement> switchElement = driver.findElements(By
.cssSelector("div.has-switch.switch-on.switch-animate"));
System.out.println(switchElement.size() + " : Switch Size");
// Check its on, if its on then switch it off
if (switchElement.size() != 0) {
switchElement.get(0)
.findElement(By.cssSelector("span.switch-left")).click();
} else
System.out.println("Switch is already off");