Check if element exists - selenium / javascript / node-js

后端 未结 6 1443
花落未央
花落未央 2020-12-14 12:21

I\'m trying to check if an element exists before I can execute this line:

driver.findElement(webdriver.By.id(\'test\'));

This throws an error \"

6条回答
  •  再見小時候
    2020-12-14 13:19

    You can leverage the optional error handler argument of then().

    driver.findElement(webdriver.By.id('test')).then(function(webElement) {
            console.log('Element exists');
        }, function(err) {
            if (err.state && err.state === 'no such element') {
                console.log('Element not found');
            } else {
                webdriver.promise.rejected(err);
            }
        });
    

    I couldn't find it explicitly stated in the documentation, but determined this from the function definition in webdriver/promise.js in the selenium-webdriver module source:

      /**
       * Registers a callback on this Deferred.
       * @param {Function=} opt_callback The callback.
       * @param {Function=} opt_errback The errback.
       * @return {!webdriver.promise.Promise} A new promise representing the result
       *     of the callback.
       * @see webdriver.promise.Promise#then
       */
      function then(opt_callback, opt_errback) { 
    

提交回复
热议问题