Search code examples
rubyseleniumwatir

How to check whether Bottom of the page reached when I do scrolling


I have to take the screenshot of the whole page, but I couldn't do that successfully(Only Firefox driver supports to take the full screenshot). So I want to split the page as top, centre, bottom and save it as three screenshots but the problem here is, If I write the below code

require 'watir'
b=Watir::Browser.new
b.scroll.to :top
b.screenshot.save("top.png")
b.scroll.to :center
b.screenshot.save("center.png")
b.scroll.to :bottom
b.screenshot.save("bottom.png")

Unfortunately, the aforementioned code takes three screenshots no matter whether the page needs to be scrolled or not. So my question is, Is there any way I can know whether Page has reached the bottom?


Solution

  • You could get the window height, as well as the body content height, to approximate how many screenshots you need. I say "approximate" since the methods for getting the heights have various caveats, eg handling scrollbars. Unless you really need pixel perfect screenshots, this approximation should be good enough.

    # Determine how many screenshots are needed to get all of the content
    window_height, content_height = b.execute_script('return [window.innerHeight, document.body.clientHeight];')
    screenshot_pieces = content_height / window_height.to_f
    
    # Always take a screenshot of the top
    b.scroll.to :top
    b.screenshot.save('top.png')
    
    # If there are more than 2 pieces, take a screenshot of the center
    if screenshot_pieces > 2 
      b.scroll.to :center
      b.screenshot.save('center.png')
    end
    
    # If there are more than 1 piece, take a screenshot of the bottom
    if screenshot_pieces > 1
      b.scroll.to :bottom
      b.screenshot.save('bottom.png')
    end
    

    You can tweak the above conditions to your liking. For example, if you don't want your screenshots to have overlapping parts (ie don't care about fractional parts of the page), you can change the conditions to screenshot_pieces >= 3 and screenshot_pieces >= 2 respectively.