How to scroll while waiting for an element

MP
2 min readOct 26, 2018

--

How do you verify element is present on the page while it is in nonvisible area of the page

Typically when doing Mobile automation, one would try to wait for an element on a page in visible area.

For this we would use wait.util alongside expected conditions as follows

from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))

But, on mobile device screen size is limited and there are chances some elements are present somewhere down in the nonvisible area. In this case we need to scroll to that element which cannot happen while we are waiting.

What typically one needs to do in this scenario is to write a wait loop with max timeout and scroll down the page while checking for element.

This works but is suboptimal. Instead of that Wait.util provides a possibility to write custom waits.

To implement custom wait one needs to write custom Expected condition. A custom wait condition can be created using a class with __call__ method which returns False when the condition doesn’t match.

For our requirement we need to write as follows —

class element_present_after_scrolling(object):
"""An expectation for checking that an element is present
locator - used to find the element
returns the WebElement once it has the particular element
"""
def __init__(self, locator, driver):
self.locator = locator
self.driver = driver
def __call__(self, driver):
self.driver._debug("element_present_after_scrolling::Finding Elements")
elements = driver.find_elements(*self.locator) # Finding the referenced element
if len(elements) > 0:
return elements
else:
self.driver.swipe_by_percent(50,90,50,10)

In the above example we are swiping the screen up to check for presence of element.

In the wait.until we would be using this new expected condition as follows —

elements = wait.until(element_present_after_scrolling((By.XPATH, xpath), driver))

Now when you run this code the page will start scrolling if the element is not found in nonvisible area

Happy Coding!!

--

--

MP
MP

Written by MP

Startup guy. Loves Programming

No responses yet