How do I use Python Selenium to check if an element is present on a webpage?

How do I use Python Selenium to check if an element is present on a webpage?

To check if an element is present on a webpage using Python Selenium, you can use the find_elements method to find all elements matching a specified locator. If the list of elements is not empty, it means the element is present.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.example.com')

elements = driver.find_elements_by_xpath('//div[@id="my-element"]')
if len(elements) > 0:
    print("Element is present")
else:
    print("Element is not present")

driver.quit()

To check if an element is present on a webpage using Python Selenium, you can use try-except block: try-except block to catch the NoSuchElementException that is raised when the element is not found. If no exception is raised, it means the element is present.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Chrome()
driver.get('https://www.example.com')

try:
    element = driver.find_element_by_xpath('//div[@id="my-element"]')
    print("Element is present")
except NoSuchElementException:
    print("Element is not present")

driver.quit()

Using find_element method and checking for None: Use the find_element method and check if the returned element is not None. If the element is not None, it means the element is present.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.example.com')

element = driver.find_element_by_xpath('//div[@id="my-element"]')
if element is not None:
    print("Element is present")
else:
    print("Element is not present")

driver.quit()