Verify that an element exist in Selenium 2 or not

0 votes

In Selenium 2, I want to ensure that an element present on the page, that the driver has loaded does not exist.

Below is my code:

    WebElement deleteLink = null;
    try {
        deleteLink = driver.findElement(By.className("commentEdit"));
    } catch (NoSuchElementException e) {

    }
    assertTrue(deleteLink != null);

Is there a more elegant way that basically verifies to assert that NoSuchElementException was thrown?

Aug 23, 2018 in Selenium by Martin
• 4,220 points
244 views

1 answer to this question.

0 votes

If you are testing using JUnit and that is the only thing you are testing you could make the test expect an exception using

@Test (expected=NoSuchElementException.class)
public void someTest() {
    driver.findElement(By.className("commentEdit"));
}

Or you could use the findElements method that returns a list of elements or an empty list if none are found (does not throw NoSuchElementException):

List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
assertTrue(deleteLinks.isEmpty());

or

 assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());

answered Aug 23, 2018 by Meci Matt
• 9,420 points

Related Questions In Selenium

0 votes
0 answers
+4 votes
3 answers

Verifying whether an element present or visible in selenium Webdriver

Below code will help you: To check Element ...READ MORE

answered Apr 17, 2018 in Selenium by king_kenny
• 3,650 points
17,809 views
0 votes
2 answers

Finding an element in Selenium

Hi, ​both find_element_by_xpath(xpath) and find_element(By.XPath, xpath) serve the ...READ MORE

answered Aug 23 in Selenium by Abha
• 27,180 points
138 views
0 votes
1 answer

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,110 points
1,009 views
0 votes
1 answer
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,130 points
1,154 views
0 votes
1 answer

How to use such xpath to find web elements

It's much simpler to use: #MyDiv123 > div.super or ...READ MORE

answered Jun 14, 2018 in Selenium by Samarpit
• 5,130 points
894 views
0 votes
1 answer

Check that the element is clickable or not in Selenium WebDriver

Use Selenium Waits: WebDriverWait ...READ MORE

answered Jun 12, 2018 in Selenium by Meci Matt
• 9,420 points
10,786 views
0 votes
1 answer

Wait til an element appears in Selenium?

You should call ignoring with exception to ignore till ...READ MORE

answered May 24, 2018 in Selenium by Meci Matt
• 9,420 points
40 views