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_elements_by_css_selector() function.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://theprogrammingexpert.com/")
if driver.find_elements_by_css_selector("h1"):
print("element 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_elements_by_css_selector() function.
If the element exists, then find_elements_by_css_selector() will return a list with those elements. If the element doesn’t exist, then find_elements_by_css_selector() function will return an empty list.
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("http://theprogrammingexpert.com/")
if driver.find_elements_by_css_selector("h1"):
print("element found!")
#Output:
element found!
One thing to note here is that you need to use the find_elements_by_css_selector() function and not find_element_by_selector().
With the latter, if the element is not found, then an exception will be thrown and your code will have an error.
Hopefully this article has been useful for you to learn how to check if an element exists when using Selenium in Python.
Leave a Reply