admin管理员组

文章数量:1357402

How can I check if an element exists in selenium?

I have tried:

browser.driver.findElements(by.id('my-id'))

but it does not seem to work.

How can I check if an element exists in selenium?

I have tried:

browser.driver.findElements(by.id('my-id'))

but it does not seem to work.

Share Improve this question edited Aug 14, 2014 at 8:53 Barney Szabolcs asked Aug 12, 2014 at 14:59 Barney SzabolcsBarney Szabolcs 12.6k15 gold badges70 silver badges97 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

Use isElementPresent

browser.driver.isElementPresent(by.id('my-id'))

or isPresent

element(by.id('my-id')).isPresent()

The problem is looking for an element that does not exist throws an exception. You ar eon the right track with using findElements as this will not throw an error if it cannot find the element, the problem you have is being left with a list that contains the elements found but not paring to make sure that there is at least 1 element in the list (e.g. it found one element)

public boolean exists(By by){
return !driver.findElements(by).isEmpty(); 
}

is a function that will return true if it exists, false otherwise. Its clear from this method how you could modify it to suit your need.

webdriver.js example

In this example I am waiting for a modal to exist because its a modal that fades in

See the line that reads const doesModalFadeInExist = await this.driver.executeScript('return document.getElementsByClassName("modal fade in")');

You can put this line of code in a wait that waits for the element array to be >=1

This way you know it is there after checking inside the wait.

We can also check opacity at the same time.

Once the element array >=1 and opacity = '1' . then we exit the wait and continue the test

async waitForModalFadeIn() {
        try {
          let isVisible;
          let opacityReturned;
          let isModalFadeInFound;
          const dialog = await this.driver.wait(until.elementLocated(this.baseselector.MODAL_FADE_IN));
          await this.driver.wait(async () => {
            const doesModalFadeInExist = await this.driver.executeScript('return document.getElementsByClassName("modal fade in")');
            isModalFadeInFound = doesModalFadeInExist;
            const bool = await this.isDisplayed(this.baseselector.MODAL_FADE_IN);
            isVisible = bool;
            const opacity = await dialog.getCssValue('opacity');
            opacityReturned = opacity;
            return isVisible === true && isModalFadeInFound.length > 0 && opacity === '1';
          }, 4000);
          return opacityReturned === '1' && isVisible === true && isModalFadeInFound.length > 0;
        } catch (err) {
          console.log(`Function waitForModalFadeIn: Failed to open modal${err}`);
          return null;
        }
      }

Example Test

    it('Trigger "unmetered" modals in the technical spec section', async () => {
        await wHost.visit(page = '/web-hosting');
        const table = await driver.wait(until.elementLocated(wHost.selector.COMPETITOR_TABLE), this.pageLoadTimeOut);
        await driver.executeScript('arguments[0].scrollIntoView()', table);
        const modals = await table.findElements(wHost.selector.UNLIMITED_MODAL);
        for (let i = 0; i < modals.length; i++) {
          await modals[i].click();
          assert.isTrue(await mon.waitForModalFadeIn());
          assert.isTrue(await mon.closeModal());
        }
      }); 

This is what you are looking for, This function takes id as parameter, If the element is found it returns json object with status=true and element you were looking for.

async function ElementExistsID(element){
    return new Promise(async (resolve)=>{
        try{
            let ElementResult=await driver.findElement(webdriver.By.id(element));
            resolve({"element":ElementResult,"status":true});
        }
        catch(error){
            log.warn(error);
            resolve({"status":false});
        }
    })
}

You can use it like this

let ElementIamLookingFor=await ElementExistsID(IDOfTheElement);
if(ElementIamLookingFor.status){
    console.log("Element exists");
}
else{
    throw new Error("Element not found");
}

After many attempts, the following worked for me:

function doIfPresent(elementId, doIfPresent, next) {
  var elem = by.id(elementId);
  browser.driver.isElementPresent(elem).then(function (present){
    if (present) {
      doIfPresent(element(elem));
    }
    next();
  });
}

eg.

doIfPresent('my-button', function(element){ element.click();}, function(){
  // your code continues here
});

I don't get it though why we'd need to use futures here.

本文标签: seleniumWebDriver in javascript how to check if an element existsStack Overflow