如何使用红宝石中的硒向下滚动到底部

时间:2014-04-18 19:35:06

标签: ruby selenium scroll selenium-webdriver

您能告诉我在ruby中使用selenium向下滚动到页面底部的方法吗?我读了这个

element = driver.find_element(:xpath, "//div[@class='footer small']")
element.location_once_scrolled_into_view

但在此link中,我无法找到任何元素。你能告诉我没有找到的元素的方式吗?谢谢!

1 个答案:

答案 0 :(得分:5)

当我查看页面时,我没有看到带有类页脚的div。这可能是您无法找到元素的原因。

对我来说,最后一个可见元素似乎是壁纸 - 即div与类pic。您可以使用以下内容获取最后一张图片并滚动到它。请注意,我们会找到所有图片,然后在集合中选择最后一张图片。

last_picture = driver.find_elements(:css, 'div.pic').last
last_picture.location_once_scrolled_into_view

滚动到最后一个壁纸后,您将需要等待页面完成加载。例如,以下内容将等到图像数量增加:

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.navigate.to 'http://www.mobileswall.com/'

# Check how many elements are there initially  
puts driver.find_elements(:css, 'div.pic').length
#=> 30

# Scroll to the last image
driver.find_elements(:css, 'div.pic').last.location_once_scrolled_into_view

# Wait for the additional images to load
current_count = driver.find_elements(:css, 'div.pic').length
until current_count < driver.find_elements(:css, 'div.pic').length
  sleep(1)
end

# Check how many elements are there now
puts driver.find_elements(:css, 'div.pic').length
#=> 59