Selenium: Check Element Exists

In Selenium, we can use the find_elements method to check if an element exists.

from selenium import webdriver

driver = webdriver.Chrome()

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

elements = driver.find_elements_by_xpath('//div[@class="example"]')

if len(elements) > 0:
    print("元素存在")
else:
    print("元素不存在")

driver.quit()

In the example above, we used the find_elements_by_xpath method to locate elements based on XPath, and then determined if the element exists by checking the length of the returned element list. If the length of the list is greater than 0, the element exists; otherwise, it does not.

bannerAds