滚动时如何检查是否到达页面底部

时间:2020-09-01 14:51:07

标签: ruby selenium watir

我必须拍摄整个页面的屏幕截图,但是我无法成功完成此操作(仅Firefox驱动程序支持拍摄完整的屏幕截图)。所以我想将页面分为顶部,中间,底部并将其另存为三个屏幕截图,但是这里的问题是,如果我编写下面的代码

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")

不幸的是,无论页面是否需要滚动,上述代码都需要三个屏幕截图。所以我的问题是,有什么办法可以知道Page是否已触底?

2 个答案:

答案 0 :(得分:1)

您可以获取窗口高度以及正文内容的高度,以近似估算所需的屏幕截图数量。我说“近似”是因为获取高度的方法有各种警告,例如处理滚动条。除非您真的需要像素完美的屏幕截图,否则这种近似应该足够好。

# 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

您可以根据自己的喜好调整上述条件。例如,如果您不希望屏幕截图包含重叠的部分(即不关心页面的小数部分),则可以将条件分别更改为screenshot_pieces >= 3screenshot_pieces >= 2

答案 1 :(得分:0)

您可以获取元素的位置,尝试向下滚动并查看元素位置是否已更改。如果不是这样,您可能处于“底线”,但潜在的警告太多了,这种情况将取决于上下文。