如何根据拨动开关的状态单击?

How do I click depending on state of toggle switch?

我有一个切换开关,我想根据开关状态点击它。

如果是"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">&nbsp;</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>

您可能想 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')]

假设文本是可靠的,您可以为此使用 xpath 选择器:

findElement(By.xpath("//span[contains(@class, 'switch-') and contains(text(), 'OFF')]")).click();

这将始终单击 OFF 开关。

您可以通过以下代码检查开关状态,并可以将其关闭

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");