In our previous post, we have discussed how to use explicit wait in selenium with python, python library provides many different conditions to wait for an element.
Still if one likes to customise & create their own webdriverwait conditions, you can!
Let’s first understand the logic behind webdriverwait implementation
If you go to the implementation of below line –
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "someXPATH")))
# expected_conditions.py # from selenium class presence_of_element_located(object): """ An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator)
From the above code, we can get to know
__call__ method will continue polling and verifying the condition till it returns false, comes out of wait once the condition is true
Polling happens in each 0.5 seconds
If the condition is never false, then it won’t continue polling rather will throw TimeOutException once the wait time passes. [mentioned as in the WebDriverWait(driver, someTime)]
So we will create our own webdriverwait condition by using above logic –
We will use this demo portal – https://qavbox.github.io/demo/delay/
If you click on the Click me button, there will be paragraph text displayed after 5 sec.
We have to wait till the text appears on browser screen and then get the text.
class wait_till_text_appears(object): def __init__(self, locator, text_): self.locator = locator self.text = text_ def __call__(self, driver): try: element_text = driver.find_element(*self.locator).text # print("Polllllllll" + element_text) return self.text in element_text except BaseException: return False
This above will accept 2 parameters, locator for which we need to get the text and the text string
__call__ method will verify if the locator text matched to the text string,
return self.text in element_text – if the text not yet appeared, then this method will return false and will poll or wait till it returns true i.e – wait till the text matches
How to use this above customised wait method?
WebDriverWait(driver, 10).until(wait_till_text_appears((By.XPATH, "//p[@id='two']"), "here!"))
Complete code –
def test_Sample1(): driver = webdriver.Chrome("/Users/skpatro/sel/chromedriver") driver.get("https://qavbox.github.io/demo/delay/") driver.find_element_by_css_selector("[value=''Click me!]").click() print("Before waiting - " + driver.find_element_by_id("two").text) WebDriverWait(driver, 10).until(wait_till_text_appears((By.XPATH, "//p[@id='two']"), "here!")) # above line will wait till the text apears print("After waiting - " + driver.find_element_by_id("two").text)
Hope this helps!