To check if an element exists in a web page when using the Python Selenium module, the easiest way is with the Selenium webdriver find_element() or find_elements() functions.
find_element() returns a single element if it is found, and find_elements() returns a list if the elements are found. If elements are not found, a NoSuchElementException is raised.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
try:
content = driver.find_element(By.CSS_SELECTOR,"h1"):
print("element found!")
except:
print("element not found")
#Output:
element found!
The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browsers.
When working with a web page, sometimes it can be useful to check if an element exists.
The easiest way to check if an element exists in a web page is with the Selenium webdriver find_element() function. You can pass “By.CSS_SELECTOR” to find an element by a css selector.
If the element exists, then find_element() will return that element. If the element doesn’t exist, then find_element() raises a NoSuchElementException.
Therefore, you need to wrap the code in a try/except block.
Below is a simple example showing you how to check if an element exists in a web page using Selenium in Python.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
try:
content = driver.find_element(By.CSS_SELECTOR,"h1"):
print("element found!")
except:
print("element not found")
#Output:
element found!
If you want to get all elements by a certain css selector, then you can use the find_elements() function. find_elements() returns a list of elements if they exist.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://daztech.com/")
try:
content = driver.find_elements(By.CSS_Selector,"h1"):
print("element found!")
except:
print("element not found")
#Output:
element found!
Hopefully this article has been useful for you to learn how to check if an element exists when using Selenium in Python.