Предупреждение о необработанном обещании отказа - Node.js - PullRequest
0 голосов
/ 25 мая 2018

Я пытаюсь заставить 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, яВсе еще изучаю.Может кто-нибудь объяснить?

1 Ответ

0 голосов
/ 25 мая 2018

В селене driver.wait возвращает IThenable или Promise.Обещания - это просто способ выполнять асинхронное программирование в javascript, и они имеют две функции, then и `catch, последнее - это то, как вы будете обрабатывать отклонения (ошибки) внутри обещаний.Итак, ваш код должен выглядеть примерно так:

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
});

Для дальнейшего ознакомления я считаю эту статью хорошим введением в обещания.

Обновление

Скорее всего, ваша проблема связана с тем, что вы пытаетесь click до того, как кнопка будет расположена, поэтому, поскольку ваш driver.wait возвращает WebElementPromise (обещание WebElement), есть дваварианты:

1.Promise.then

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.Синтаксис await

Примечание: Это доступно только для 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: Поскольку вы говорите, что еще учитесь Я предполагаю, что здесь есть термины, которые могут не знать, правда ли это, я рекомендую вам провести исследование.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...