scroll up the page to the top in selenium

牧云@^-^@ 提交于 2020-05-12 11:37:10

问题


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)

just like that is it possible to scroll the page to the top


回答1:


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); 



回答2:


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)");



回答3:


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

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



回答4:


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)");



回答5:


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);



来源:https://stackoverflow.com/questions/36647785/scroll-up-the-page-to-the-top-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!