Checking if element exists with Python Selenium
Solution 1:
a)
from selenium.common.exceptions import NoSuchElementException
def check_exists_by_xpath(xpath):
try:
webdriver.find_element_by_xpath(xpath)
except NoSuchElementException:
return False
return True
b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.
UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.
Solution 2:
None of the solutions provided seemed at all easiest to me, so I'd like to add my own way.
Basically, you get the list of the elements instead of just the element and then count the results; if it's zero, then it doesn't exist. Example:
if driver.find_elements_by_css_selector('#element'):
print "Element exists"
Notice the "s" in find_elements_by_css_selector
to make sure it can be countable.
EDIT: I was checking the len(
of the list, but I recently learned that an empty list is falsey, so you don't need to get the length of the list at all, leaving for even simpler code.
Also, another answer says that using xpath is more reliable, which is just not true. See What is the difference between css-selector & Xpath? which is better(according to performance & for cross browser testing)?
Solution 3:
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 2 reasons:
- the text is more likely to change and;
- if it is important to you, you won't be able to run your tests against localized builds.
solution either:
- You can use xpath to find a parent or ancestor element that has an ID or some other unique identifier and then find it's child/descendant that matches or;
- 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
Solution 4:
Solution without try&catch and without new imports:
if len(driver.find_elements_by_id('blah')) > 0: #pay attention: find_element*s*
driver.find_element_by_id('blah').click #pay attention: find_element
Solution 5:
The same as Brian, but add to this answer from tstempko:
https://sqa.stackexchange.com/questions/3481/quicker-way-to-assert-that-an-element-does-not-exist
So I tried and it works quickly:
driver.implicitly_wait(0)
if driver.find_element_by_id("show_reflist"):
driver.find_element_by_id("show_reflist").find_element_by_tag_name("img").click()
after this I restore my default value
driver.implicitly_wait(30)