Scroll Element into View with Selenium

前端 未结 30 2321
时光说笑
时光说笑 2020-11-22 08:31

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus m

30条回答
  •  感情败类
    2020-11-22 09:16

    From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).

    I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;

    class Element
    
          #
          # Alias the original click method to use later on
          #
          alias_method :base_click, :click
    
          # Override the base click method to scroll into view if the element is not visible
          # and then retry click
          #
          def click
            begin
              base_click
            rescue Selenium::WebDriver::Error::ElementNotVisibleError
              location_once_scrolled_into_view
              base_click
            end
          end
    

    The 'location_once_scrolled_into_view' method is an existing method on WebElement class.

    I apreciate you may not be using Ruby but it should give you some ideas.

提交回复
热议问题