Selenium 为什么isDisplayed使用定位器而不是布尔值返回未找到的元素量角器

Selenium 为什么isDisplayed使用定位器而不是布尔值返回未找到的元素量角器,selenium,typescript,webdriver,protractor,Selenium,Typescript,Webdriver,Protractor,我有一个方法isElementDisplayed,其中包含元素。isDisplayed内部调用 当可以返回布尔值时,isDisplayed为什么返回No-element found isElementDisplayed(element: ElementFinder) { return element.isDisplayed(); } find元素引发了异常。使用try&catch块返回false try{ return element.isDisplayed(); } catch (

我有一个方法
isElementDisplayed
,其中包含
元素。isDisplayed
内部调用

当可以返回布尔值时,
isDisplayed
为什么返回
No-element found

isElementDisplayed(element: ElementFinder) {
    return element.isDisplayed();
}

find元素引发了异常。使用try&catch块返回false

try{
return element.isDisplayed();
} 
catch (Exception e) 
{
return false; 
// e.getMessage(); // you can console the exception message if required
}

您应该尝试全局方法,并在需要时调用它。大概是这样的:

public static boolean ElementVisible(By element, WebDriver driver) {

        // Maximum wait time is 60 seconds
        int maxAttempts = 2;
        long sleepTimeInMillisForEachIteration = 500;

        for (int counter = 0; counter <= maxAttempts; counter++) {
            try {

                    driver.findElement(element);        

                return true;
            } catch (NoSuchElementException | ElementNotVisibleException e) {
                if (counter == maxAttempts) {
                    return false;
                }
                try {
                    Thread.sleep(sleepTimeInMillisForEachIteration);
                    continue;
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return false;
    }
公共静态布尔元素可见(按元素、WebDriver驱动程序){
//最长等待时间为60秒
int=2;
长睡眠时间(单位:毫秒)再加速=500;
对于(int counter=0;counter将检查元素是否可见,但您需要检查元素是否存在于DOM中,请使用或:

另见:


  • 在幕后,首先要找到元素的元素。只有在找到元素之后,它才会显示元素是否被显示。当它查看元素是否存在时,它没有,并且抛出异常。这是一个查找优先级。是的,理论上,硒可以返回一个布尔值,但是考虑一下它给了你m。比你要求的更多的信息!Colud你告诉我如何在typescript中写“if element not visible return boolean”?我不熟悉该语言,但建议使用try/catch机制。在
    try
    块中,完全按照您上面所写的操作。在
    catch
    块下,检查异常是否为“未找到元素”,如果是这种情况,则返回
    false
    。如果try-get-error I,我无法在catch块中获得错误将看到未找到元素…catch块未执行…(TypeScript)
    expect(browser.isElementPresent(element(by.id('ELEMENT_ID_HERE')))).toBe(false);
    expect(element(by.id('ELEMENT_ID_HERE')).isPresent()).toBe(false);