Webdriver: Check If an Element Exists

How can I check if an element exists with Selenium WebDriver?

You could alternatively do:

driver.findElements(By.id("...")).size() != 0

Which saves the nasty try/catch

P.S.:

Or more precisely by @JanHrcek here

!driver.findElements(By.id("...")).isEmpty()

Test if an element is present using Selenium WebDriver

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception.

To check that an element is present, you could try this

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

This will return true if at least one element is found and false if it does not exist.

The official documentation recommends this method:

findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.

Selenium check if element exists without exception

Instead of driver.find_element you should use driver.find_elements method here.

Something like this:

if driver.find_elements_by_xpath("/div[@class='class_name']"):
driver.find_element_by_xpath("/div[@class='class_name']").click()

Or this:

elements = driver.find_elements_by_xpath("/div[@class='class_name']")
if elements:
elements[0].click()

driver.find_elements will return you a list of web elements matching the passed locator. In case such elements found it will return non-empty list interpreted by Python as a Boolean True while if no matches found it will give you an empty list interpreted by Python as a Boolean False

How to check if an element exists in the HTML using Selenium

To attempt to find an element on the pages using the class and display the text from there irrespective of the element being present or not you can wrap up the code in a try-except{} block handling the NoSuchElementException as follows:

driver.get(url=urlik)
time.sleep(2)
try:
urla = driver.find_element(By.CLASS_NAME, "ipsPagination_pageJump").text
for page_number in range(int(urla.split()[3])):
page_number = page_number + 1
driver.get(url=urlik + f"page/{page_number}")
time.sleep(2)
imgs = driver.find_elements(By.CLASS_NAME, "cGalleryPatchwork_image")
for i in imgs:
driver.execute_script("arguments[0].scrollIntoView(true);", i)
time.sleep(0.2)
print(i.get_attribute("src"))
except NoSuchElementException:
print("Element is not present")

How to check if an element exists?

You can check if an element exits or not by using

bool isElementDisplayed = driver.findElement(By.xpath("element")).isDisplayed()

Remember, findElement throws an exception if it doesn't find an element, so you need to properly handle it.

In one of my applications, I handled an exception by checking the element in a separate function:

private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}

Call function:

if (IsElementPresent(By.Id("element name")))
{
// Do if exists
}
else
{
// Do if does not exists
}

Checking if an element exists with Python Selenium

A) Yes. The easiest way to check if an element exists is to simply call find_element inside a try/catch.

B) Yes, I always try to identify elements without using their text for two reasons:

  1. the text is more likely to change and;
  2. if it is important to you, you won't be able to run your tests against localized builds.

The solution is either:

  1. You can use XPath to find a parent or ancestor element that has an ID or some other unique identifier and then find its child/descendant that matches or;
  2. you could request an ID or name or some other unique identifier for the link itself.

For the follow-up questions, using try/catch is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html

How do I determine if a WebElement exists with Selenium?

Best practice is to do what you originally suggested. Use .findElements() and check for .size != 0, or you can also use my preference, .isEmpty(). You can create a utility function like the below to test if an element exists.

public boolean elementExists(By locator)
{
return !driver.findElements(locator).isEmpty();
}

You could also build this into a function in your page object.

Check if element exists python selenium

You can implement try/except block as below to check whether element present or not:

from selenium.common.exceptions import NoSuchElementException

try:
element=driver.find_element_by_partial_link_text("text")
except NoSuchElementException:
print("No element found")

or check the same with one of find_elements_...() methods. It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found:

elements=driver.find_elements_by_partial_link_text("text")
if not elements:
print("No element found")
else:
element = elements[0]


Related Topics



Leave a reply



Submit