Javascript 如果元素未与isDisplayed()一起显示,则I';我出错了

Javascript 如果元素未与isDisplayed()一起显示,则I';我出错了,javascript,selenium,selenium-webdriver,Javascript,Selenium,Selenium Webdriver,我的场景 访问特定页面 在显示元素时,是否应单击它 如果不显示此元素,请忽略 我的代码 exports.checkButton = function (driver) { driver.findElement(By.css(".btn.btn-danger.pull-right.remove-promotion")).then(function(button){ if (button.isDisplayed()) { console.log

我的场景

  • 访问特定页面
  • 在显示元素时,是否应单击它
  • 如果不显示此元素,请忽略
  • 我的代码

    exports.checkButton = function (driver) {
    
        driver.findElement(By.css(".btn.btn-danger.pull-right.remove-promotion")).then(function(button){ 
    
            if (button.isDisplayed()) {
    
                console.log("Displaying"); 
    
        } else { 
    
                console.log("not displayed");
    
        }
    });
    
    我的问题

    如果元素未显示,则不会显示消息
    console.log(“未显示”)我得到一个错误:

    Uncaught NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":".btn.btn-danger.pull-right.remove-promotion"}
    

    如果要确保显示元素,首先需要确保它确实存在于DOM中。在Java中,您可以这样检查:

    public boolean isElementPresentInDom(By by) {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
        boolean isElementPresent = (driver.findElements(by).size() != 0);
        driver.manage().timeouts().implicitlyWait(driverTimeOut, TimeUnit.MILLISECONDS); // I have a driverTimeOut variable, I set the default timeout to zero in the beginning of this method to make it fast, then I set it to my driverTimeOut again. I recommend you to do the same :)
        return isElementPresent;
    }
    
    (不知道如何准确地用Javascript翻译,但你已经掌握了主要思想。) 如果此方法返回
    true
    ,则可以检查是否显示元素

    使用
    .isDisplayed()
    假定元素存在。因为元素不存在,所以会出现该错误。您的定位器已关闭或元素可能尚未加载,等等。请使用
    .findElements()
    (复数)并确保大小>0以查看元素是否存在。理想情况下,您可以将其包装在函数中,并在需要时使用它。一旦确定元素存在,然后选中
    .isDisplayed()
    ,代码应该可以工作。

    isDisplayed()
    只能在元素存在于DOM中时使用,但可以隐藏(例如,包含
    style=“display:none”
    )。 我认为,在您的例子中,当元素不显示时,它在DOM中不存在,这就是为什么会出现异常NoTouchElementError

    请尝试:

    export.checkButton = function (driver) {    
            driver.findElement(By.css(".btn.btn-danger.pull-right.remove-promotion")).then(function(button){ 
                console.log("Displaying");
                button.click();
                return true;
            }).catch(function (ex) {
                console.log("not displayed");
                return false;
            });
    }
    
    var display = checkButton(driver);
    while (display) {
        display = checkButton(driver);
    }
    

    注意:您应该首先检查DOM,看看它在这两种情况下的行为-当元素存在和不存在时。

    检查这个问题事实上我需要在while中使用这个catch。例如,当按钮存在时,运行
    console.log(“显示”)
    。你有这方面的例子吗?因为我在这里尝试但没有成功所以你使用我上面的代码却没有成功?它显示了什么?有错误吗?您是否检查了css是否正确?@LihnNguyen您的代码工作得很好,但我需要在显示
    按钮时使用
    while
    catch
    多次执行块代码。示例?如果元素存在,我用
    click()
    更新了代码。我不明白你为什么需要
    呢?也许您可以更新您的场景?因为这是一个包含多个条目的页面,所以在显示这些记录时,我需要删除它们,当它不再存在时,我运行catch:)