Javascript 如何处理量角器中未找到元素异常

Javascript 如何处理量角器中未找到元素异常,javascript,selenium,selenium-webdriver,protractor,Javascript,Selenium,Selenium Webdriver,Protractor,就像SeleniumWebDriver为Java提供了各种异常处理一样,我们是否可以通过使用量角器实现同样的效果 如果我们想处理元素未找到异常,那么使用量角器的最佳方法是什么?回答这个问题 如何捕获ElementNotFound之类的错误? 当命令无法完成时,WebDriver会抛出错误-例如,无法单击被另一个元素遮挡的元素。如果需要重试这些操作,请尝试使用。如果您只想捕捉错误,请这样做 根据你的问题: elm.isPresent().then(function(present) { /*

就像SeleniumWebDriver为Java提供了各种异常处理一样,我们是否可以通过使用量角器实现同样的效果

如果我们想处理元素未找到异常,那么使用量角器的最佳方法是什么?

回答这个问题

如何捕获ElementNotFound之类的错误? 当命令无法完成时,WebDriver会抛出错误-例如,无法单击被另一个元素遮挡的元素。如果需要重试这些操作,请尝试使用。如果您只想捕捉错误,请这样做

根据你的问题:

elm.isPresent().then(function(present) {
  /* no webdriver js errors here */}
  if (present) {
    /* element exists */
  } else {
    /* element doesn't exist */
  }
, function(err) {
  /* error handling here, i.e. element doesn't if got ElementNotFound
     but, eventually and less likely, other issues will fall in here too like
     NoSuchWindowsError or ElementStaleError etc...
  */
});

Try,Catch在量角器中具有以下语法。下面的代码将首先找到Id为“IdTextBoxCode”的元素。然后输入代码“codeTextBox.sendKeys(代码);”在TRY块中。如果代码引发异常(在本例中,如果未找到Id为“IdTextBoxCode”的元素),则它将转到catch块和错误处理函数

browser.driver.findElement(by.id(browser.params.loginPage.IdTextBoxCode)).then(function(codeTextBox)
    {
        try 
        {
            console.log("Entering Code: "+code);
            codeTextBox.sendKeys(code);
        }
        catch(err) {
            console.log('In catch block');
        }
   }, function(err) {
        console.info('Code Text Box not displayed on page. Proceeding with default Code');
    });

感谢@Leo Gallucci对OP问题的改编:

elm.isPresent().then(function(present) {
  /* no webdriver js errors here */}
  if (present) {
    /* element exists */
  } else {
    /* element doesn't exist */
  }
, function(err) {
  /* error handling here, i.e. element doesn't if got ElementNotFound
     but, eventually and less likely, other issues will fall in here too like
     NoSuchWindowsError or ElementStaleError etc...
  */
});
我今天面对这个问题,希望能找到一个干净的解决方案,就像这样:

/*函数检查三个可能的DOM元素;返回存在的元素,并获取文本内容*/
this.getMySelector=函数(){
if(元素(by.css('.mySelector')).isPresent(){
返回元素(by.css('.mySelector');
}
else if(元素(by.css('.mySelector2')).isPresent()){
返回元素(by.css('.mySelector2');
}
否则{
返回元素(by.css('.mySelector3');
}

}
Hmm。。。您可以编辑您的问题,添加代码,并给我们更多的细节请?非常及时为我张贴。这很有帮助。