Sun*_*tro 0 javascript node.js selenium-webdriver
我试图让 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();
Run Code Online (Sandbox Code Playgroud)
错误:
(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.
Run Code Online (Sandbox Code Playgroud)
我不知道如何处理 JS 中的错误,我仍在学习。有人可以解释一下吗?
在 Selenium 中driver.wait返回一个IThenableor 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
});
Run Code Online (Sandbox Code Playgroud)
为了进一步参考,我发现这篇文章是对 Promise 的很好的介绍。
更新
您的问题很可能是因为您尝试click找到之前的按钮,因此,由于您driver.wait返回一个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
});
Run Code Online (Sandbox Code Playgroud)
注意:此功能仅适用于 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();
Run Code Online (Sandbox Code Playgroud)
ps:既然你说你还在学习,我想这里有些术语可能不知道这是否属实,我建议你做研究。
| 归档时间: |
|
| 查看次数: |
6330 次 |
| 最近记录: |