scroll up the page to the top in selenium

前端 未结 6 2246
北海茫月
北海茫月 2021-02-19 10:50

How to scroll the webpage to the top of the page.

I know scrolling the page to the bottom is:

window.scrollTo(0,document.body.scrollHeight)
<         


        
相关标签:
6条回答
  • 2021-02-19 11:20

    To scroll to the top of the page

    ((JavascriptExecutor) driver).executeScript("window.scrollTo(document.body.scrollHeight, 0)");
    

    To scroll to the end of the page

    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,document.body.scrollHeight)");
    
    0 讨论(0)
  • 2021-02-19 11:30

    yes you can try as below

    Way one - Scrolling to bottom of a page

    driver.navigate().to(URL);
    ((JavascriptExecutor) driver)
    .executeScript("window.scrollTo(0, document.body.scrollHeight)");
    

    Way two - Scrolling to an element on a page

    driver.navigate().to(URL);
    WebElement element = driver.findElement(By.id("id"));
            ((JavascriptExecutor) driver).executeScript(
                    "arguments[0].scrollIntoView();", element);
    

    Way 3 -Scrolling by coordinates

     driver.navigate().to(URL);
        ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
    
    0 讨论(0)
  • 2021-02-19 11:36

    simple way for the top :webDriver.FindElement(By.TagName("body")).SendKeys(Keys.Home); and for the bottom: webDriver.FindElement(By.TagName("body")).SendKeys(Keys.End);

    0 讨论(0)
  • 2021-02-19 11:38

    To scroll to the top of the page, just scroll to the 0, 0:

    window.scrollTo(0, 0);
    

    Or, as an alternative option, you can scroll into view of the header element (or some other element on top):

    WebElement element = driver.findElement(By.tagName("header"));
    
    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("arguments[0].scrollIntoView();", element); 
    
    0 讨论(0)
  • 2021-02-19 11:40

    Use action class, as some UI frameworks don't work well with JavaScript scrollTO

    actions.sendKeys(keys.Home).build().perform();
    actions.sendKeys(keys.END).build().perform();
    
    0 讨论(0)
  • 2021-02-19 11:43

    This solution also works correctly, I've checked it:

    ((JavascriptExecutor) driver)
        .executeScript("window.scrollTo(0, -document.body.scrollHeight)");
    
    0 讨论(0)
提交回复
热议问题