Search code examples
rubywebdriverwatir

Watir scroll down the page as long as there is more content to show


I want to scroll down the page as long as there is more content to show.

For example, when you click followers on Instagram, a dialog window will pop up and it will load more followers as you scroll down as long as there are more followers to show.

Instagram followers dialog window

I could do this the hard way like getting the follower count and then counting the followers as I scroll down and when they equal stop scrolling there.

But I wanted to ask you whether there could be a better way.


Solution

  • You can check if a scrollable element is at the bottom by comparing its scrollTop and scrollHeight.

    The following work:

    scrollable = browser.div(class: 'j6cq2') # div with overflow-y=scroll
    until browser.execute_script('return arguments[0].scrollTop + arguments[0].clientHeight >= arguments[0].scrollHeight', scrollable) do
        browser.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', scrollable)
        sleep(1)
    end
    

    Note that I didn't have time to find a better solution than using #sleep. However, hopefully this gives you an idea.