我正在尝试让 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
。Promises 只是在 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
返回 a WebElementPromise
(WebElement 的承诺),因此有两个选项:
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
});
注意:这仅适用于 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:既然你说你还在学习,我假设这里有一些术语可能不知道这是否属实,我建议你做研究。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句