的Watir。 滚动到页面的某个点

我试图在网站上自动进行在线调查,但每次都会出现此错误:

Selenium::WebDriver::Error::UnknownError: unknown error: Element is not clickable at point (561, 864). Other element would receive the click: a id="habla_oplink_a" class="habla_oplink_a_normal hbl_pal_header_font_size hbl_pal_title_fg " 

我需要了解的是如何滚动到页面的某个点,以便我的脚本可以恢复填写页面上的调查。

这是我的代码,它设法填写调查的一部分,但是当它到达浏览器内部不在视图中的行(需要用户向下滚动到的行)时失败:

 buttons = browser.elements(:class => "assessment-choice") buttons.each do |button| button.click end 

我还希望能够更改我的代码,以便它只选择一个特定的选项,但页面上的HTML不是很友好。

这是我正在查看的网页: https : //staging2.clearfit.com/assessment/assessment/95867fb272df436352a0bd5fbdd

调查中其中一个选项的HTML:

 Strongly
Agree

使用execute_script

要滚动到元素,您需要执行javascript:

 browser.execute_script('arguments[0].scrollIntoView();', button) 

可以看到这可以在以下脚本中使用。 如果没有要滚动的行,聊天选项卡会覆盖其中一个按钮,从而导致exception。

 require 'watir-webdriver' browser = Watir::Browser.new :chrome browser.goto 'https://staging2.clearfit.com/assessment/assessment/95867fb272df436352a0bd5fbdd' buttons = browser.elements(:class => "assessment-choice") buttons.each do |button| browser.execute_script('arguments[0].scrollIntoView();', button) button.click end 

使用watir-scroll gem

请注意,您可以安装watir-scroll gem以使滚动线更好。 gem允许线条简单地:

 browser.scroll.to button 

该脚本将如下所示:

 require 'watir-webdriver' require 'watir-scroll' browser = Watir::Browser.new :chrome browser.goto 'https://staging2.clearfit.com/assessment/assessment/95867fb272df436352a0bd5fbdd' buttons = browser.elements(:class => "assessment-choice") buttons.each do |button| browser.scroll.to button button.click end 

首先,这应该是不必要的。 根据规范 ,所有元素交互都需要隐式滚动到元素。 但是,如果某些事情确实阻止了这种情况发生,您可以使用此Selenium方法而不是javascript实现:

 buttons = browser.elements(:class => "assessment-choice") buttons.each do |button| button.wd.location_once_scrolled_into_view button.click end 
  public def scroll_to(param) args = case param when :top, :start 'window.scrollTo(0, 0);' when :center 'window.scrollTo(window.outerWidth / 2, window.outerHeight / 2);' when :bottom, :end 'window.scrollTo(0, document.body.scrollHeight);' when Array ['window.scrollTo(arguments[0], arguments[1]);', Integer(param[0]), Integer(param[1])] else raise ArgumentError, "Don't know how to scroll to: #{param}!" end @browser.execute_script(*args) end public # This method pulls the object on the page you want to interact with, then it 'jumps to it'. def jump_to(param) # Leveraging the scroll_to(param) logic, this grabs the cooridnates, # and then makes them an array that is able to be located and moved to. # This is helpful when pages are getting too long and you need to click a button # or interact with the browser, but the page 'Cannot locate element'. location = param.wd.location location = location.to_a $helper.scroll_to(location) end 

然后你只需要调用jump_to(element)并将其“跳转”到它。

这就是我如何解决它 – 不确定这是否是正常的方式。 问题是它是指向(0,0); 处理移动到中心屏幕的版本。