javascript - 未处理的承诺拒绝警告 - Node.js
问题描述
我正在尝试让 JS 加载一个网站,然后单击两个按钮。第一个按钮单击并通过,但第二个按钮发出此错误
const ATC_Button = driver.wait(
webdriver.until.elementLocated({ name: 'commit' }),
20000
);
const GTC_Button = driver.wait(
webdriver.until.elementLocated({ xpath: '//*[@id="cart"]/a[2]' }),
20000
);
ATC_Button.click();
GTC_Button.click();
错误:
(node:21408) UnhandledPromiseRejectionWarning: WebDriverError: element not visible
(Session info: chrome=66.0.3359.181)
(Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.16299 x86_64)
at Object.checkLegacyResponse (C:\New folder\JS\Bot V1\MYBot\node_modules\selenium-webdriver\lib\error.js:585:15)
at parseHttpResponse (C:\New folder\JS\Bot V1\MYBot\node_modules\selenium-webdriver\lib\http.js:533:13)
at Executor.execute (C:\New folder\JS\Bot V1\MYBot\node_modules\selenium-webdriver\lib\http.js:468:26)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:21408) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21408) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我不确定如何处理 JS 中的错误,我还在学习中。有人可以解释吗?
解决方案
在 selenium中driver.wait
返回一个IThenable
or Promise
。Promise 只是在 javascript 中进行异步编程的一种方式,它们有两个功能,then
并且 `catch,最新的是如何处理Promise 中的拒绝(错误)。因此,您的代码需要类似于:
const ATC_Button = driver.wait(
webdriver.until.elementLocated({ name: 'commit' }),
20000
).catch(function(err){
// Do something with you error
});
const GTC_Button = driver.wait(
webdriver.until.elementLocated({ xpath: '//*[@id="cart"]/a[2]' }),
20000
).catch(function(err){
// Do something with you error
});
为了进一步参考,我发现这篇文章是对 Promise 的一个很好的介绍。
更新
您的问题很可能是因为您试图找到click
之前的按钮,因此,由于您driver.wait
返回一个WebElementPromise
(WebElement 的承诺),因此有两种选择:
1. 承诺。那么
driver
.wait(webdriver.until.elementLocated({ name: "commit" }), 20000)
.then(button => button.click()) // Here the WebElement has been returned
.catch(function(err) {
// Do something with you error
});
2.等待语法
注意:这仅适用于 ES6
// Here you are waiting for the promise to return a value
const ATC_Button = await driver
.wait(webdriver.until.elementLocated({ name: "commit" }), 20000)
.catch(function(err) {
// Do something with you error
});
ATC_Button.click();
ps:既然你说你还在学习,我假设这里有一些术语可能不知道这是不是真的,我建议你做研究。
推荐阅读
- javascript - 从后端到前端的 DateTime 值
- python - 使用行的值在 pandas 中创建一个新列
- php - 使用 slugs 而不是 id
- javascript - 如何在“。”之后调用函数,javascript
- python - 使用 tkinter 的 Listbox GUI 从列表中选择项目
- powershell - 使用流水线命令同步写入 foreach 内的命令行
- python-3.x - 无法使用 Selenium-Python 打开 TOR
- android - 在 recyclerview 上更改方向期间再次从 Internet 加载数据
- javascript - 移动 iOS 和 Android Safari/Chrome 之间的 JavaScript 差异
- android - Android应用程序随机关闭而没有任何错误