【问题标题】:Selenium Crashes in Try BlockTry Block 中的 Selenium 崩溃
【发布时间】:2017-01-09 20:47:13
【问题描述】:

所以我正在使用 Selenium 的 JavaScript 实现,WebDriverJS。我对 WebDriverJS 很陌生,我想知道,为什么代码会在 Try 块中崩溃?它甚至永远不会到达 Catch 块。这是我的代码:

    try
    {
        driver.findElement(this.By.xpath("html/body/form/div[4]/div[1]/center[1]/div[15]/div[1]/a[1]/img[1]")).click();
    catch (err)
    {
        driver.findElement(this.By.xpath("html/body/form/div[3]/div[1]/center[1]/div[15]/div[1]/a[1]/img[1]")).click();
    }

然后我在控制台中收到此错误消息:

NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/form/div[4]/div[1]/center[1]/div [15]/div[1]/a[1]/img[1]"}

如您所见,此错误来自 Try 块中的代码。

有什么方法可以让代码在出现此错误的情况下继续执行?

【问题讨论】:

  • 很可能你的catch语句也抛出了错误。
  • 不,我已经测试了 catch 块中的代码,它工作正常。
  • xpath 也很挑剔。最好使用css路径,比如this.By.css("div.someClass > a > img:nth-child(2)")。您可以使用 document.querySelector("div.someClass") 在浏览器控制台中测试 CSS 路径

标签: javascript selenium selenium-webdriver try-catch


【解决方案1】:

WebdriverJS 异步触发“findElements”(docs here),这意味着您的语句将清除 try catch,然后回调抛出错误。要正确捕获错误,请使用promise pattern

// Original implementation    
driver.findElement({id: 'my-button'}).click();

// Promise usage, my preference
driver.findElement({id: 'my-button'}).then(function(el) {
  return el.click();
}).catch(function(err){
  //handle error here
})

// Another way to resolve the error
driver.findElement({id: 'my-button'}).then(el, function (err) {
  if (err && err.name === "NoSuchElementError"){
    return console.log("Element was missing!");
  }

  return el.click();  
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    相关资源
    最近更新 更多