Scroll Element into View with Selenium

前端 未结 30 2313
时光说笑
时光说笑 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:22

    Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.

    Scrolling to the element happens implicitly so you just need to find the item and then work with it.

    0 讨论(0)
  • 2020-11-22 09:24
    webElement = driver.findElement(By.xpath("bla-bla-bla"));
    ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
    

    For more examples, go here. All in Russian, but Java code is cross-cultural :)

    0 讨论(0)
  • 2020-11-22 09:24

    You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:

    public static void main(String[] args) throws Exception {
    
        // TODO Auto-generated method stub
        FirefoxDriver ff = new FirefoxDriver();
        ff.get("http://toolsqa.com");
        Thread.sleep(5000);
        ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
    }
    
    0 讨论(0)
  • 2020-11-22 09:25

    Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.

    0 讨论(0)
  • 2020-11-22 09:25

    This code is working for me:

    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("javascript:window.scrollBy(250, 350)");
    
    0 讨论(0)
  • 2020-11-22 09:26

    You can use this code snippet to scroll:

    C#

    var element = Driver.FindElement(By.Id("element-id"));
    Actions actions = new Actions(Driver);
    actions.MoveToElement(element).Perform();
    

    There you have it

    0 讨论(0)
提交回复
热议问题