How to use 'expected conditions' to check for an element in python-selenium?
Seems you were almost there.
The Documentation
clearly says the following:
class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)
Which is defined as :
An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. locator - used to find the element
returns the WebElement once it is located and visible
Hence, when you mention:
return EC.visibility_of_element_located((By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]'))
The found out WebElement
is being returned as follows :
<selenium.webdriver.support.expected_conditions.visibility_of_element_located object at 0x110321b90>
Even the Source Code
says the same as :
try:
return _element_if_visible(_find_element(driver, self.locator))
When the search is unsuccessfull :
except StaleElementReferenceException:
return False
To summarize in a more organized manner:
- Expected Condition is a callable (could be a function or a class with
__call__()
magic method defined) Expected Condition is supposed to be used inside the
until()
method of aWebDriverWait()
instance:wait = WebDriverWait(driver, 10) wait.until(<Expected_condition_here>)
the result of an Expected Condition does not have to be just
True
/False
. The result would be tested on truthiness by theWebDriverWait
. Note: aWebElement
instance is "truthy". Read more about truthiness in Python hereit is quite convenient that when an Expected Condition returns a
WebElement
instance. It allows to have a link to an element right away without the need to find it again:button = wait.until(EC.element_to_be_clickable((By.ID, "my_id"))) button.click()
- you can write your own custom Expected Conditions