简体   繁体   English

使用java在Selenium WebDriver(Selenium 2)中向上或向下滚动页面

[英]Page scroll up or down in Selenium WebDriver (Selenium 2) using java

I have written the following code in Selenium 1 (aka Selenium RC) for page scrolling using java:我在 Selenium 1(又名 Selenium RC)中编写了以下代码,用于使用 java 进行页面滚动:

selenium.getEval("scrollBy(0, 250)");

What is the equivalent code in Selenium 2 (WebDriver)? Selenium 2 (WebDriver) 中的等效代码是什么?

Scenario/Test steps:场景/测试步骤:
1. Open a browser and navigate to TestURL 1. 打开浏览器并导航到TestURL
2. Scroll down some pixel and scroll up 2.向下滚动一些像素并向上滚动

For Scroll down :对于向下滚动

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");

OR, you can do as follows:或者,您可以执行以下操作:

jse.executeScript("scroll(0, 250);");

For Scroll up :对于向上滚动

jse.executeScript("window.scrollBy(0,-250)");
OR,
jse.executeScript("scroll(0, -250);");

Scroll to the bottom of the page:滚动到页面底部:

Scenario/Test steps:场景/测试步骤:
1. Open a browser and navigate to TestURL 1. 打开浏览器并导航到TestURL
2. Scroll to the bottom of the page 2. 滚动到页面底部

Way 1: By using JavaScriptExecutor方式一:使用 JavaScriptExecutor

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

Way 2: By pressing ctrl+end方式2:按ctrl+end

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);

Way 3: By using Java Robot class方式 3:通过使用 Java Robot 类

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_CONTROL);

Scrolling to the bottom of a page:滚动到页面底部:

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

There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.在 Selenium Webdriver 中有很多上下滚动的方法,我总是使用 Java Script 来做同样的事情。

Below is the code which always works for me if I want to scroll up or down如果我想向上或向下滚动,下面是始终适用于我的代码

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

You can get full code from here Scroll Page in Selenium你可以从这里获得完整的代码Scroll Page in Selenium

If you want to scroll for a element then below piece of code will work for you.如果你想滚动一个元素,那么下面的一段代码对你有用。

je.executeScript("arguments[0].scrollIntoView(true);",element);

You will get the full doc here Scroll for specific Element您将在此处获得完整的文档滚动特定元素

This may not be an exact answer to your question (in terms of WebDriver), but I've found that the java.awt library is more stable than selenium.Keys .这可能不是您问题的确切答案(就 WebDriver 而言),但我发现java.awt库比selenium.Keys更稳定。 So, a page down action using the former will be:因此,使用前者的向下翻页操作将是:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
JavascriptExecutor js = ((JavascriptExecutor) driver);

Scroll down:向下滚动:

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

Scroll up:向上滚动:

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

Try this:尝试这个:

Actions dragger = new Actions(driver);
WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[@id='jobreslist_outercontainer']/div/div[2]/div"));

// drag downwards
int numberOfPixelsToDragTheScrollbarDown = 50;
for (int i = 10; i < 500; i += numberOfPixelsToDragTheScrollbarDown) {
    try {
        // this causes a gradual drag of the scroll bar, 10 units at a time
        dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
        Thread.sleep(1000L);
    } catch(Exception e1) {}
}

// now drag opposite way (downwards)
numberOfPixelsToDragTheScrollbarDown = -50;
for (int i = 500; i > 10; i += numberOfPixelsToDragTheScrollbarDown) {
    // this causes a gradual drag of the scroll bar, -10 units at a time
    dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
    Thread.sleep(1000L);
}
        

I did not want to use JavaScript, or any external libraries, so this was my solution (C#):我不想使用 JavaScript 或任何外部库,所以这是我的解决方案 (C#):

IWebElement body = Driver.FindElement(By.TagName("body"));

IAction scrollDown = new Actions(Driver)
    .MoveToElement(body, body.Size.Width - 10, 15) // position mouse over scrollbar
    .ClickAndHold()
    .MoveByOffset(0, 50) // scroll down
    .Release()
    .Build();

scrollDown.Perform();

You can also easily make this an extension method for scrolling up or down on any element.您还可以轻松地将其作为在任何元素上向上或向下滚动的扩展方法。

1.To scroll page to the bottom use window.scrollTo(0,document.body.scrollHeight) as parameter 1.滚动页面到底部使用 window.scrollTo(0,document.body.scrollHeight) 作为参数

//Code to navigate to bottom //代码导航到底部

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollHeight));

2.To scroll page to the top use window.scrollTo(0,document.body.scrollTop) as parameter 2.将页面滚动到顶部使用 window.scrollTo(0,document.body.scrollTop) 作为参数

//Code to navigate to top //代码导航到顶部

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollTop));

3.To scroll page to the Left use window.scrollTo(0,document.body.scrollLeft) as parameter 3.要向左滚动页面,请使用 window.scrollTo(0,document.body.scrollLeft) 作为参数

//Code to navigate to left //向左导航的代码

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollLeft));

4.To scroll to certain point window.scrollTo(0,500) as parameter 4.滚动到某个点 window.scrollTo(0,500) 作为参数

//Code to navigate to certain point eg 500 is passed as value here // 导航到某个点的代码,例如 500 在此处作为值传递

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,500));

To check the navigation directly in browser , open developers tool in browser and navigate to console.要直接在浏览器中检查导航,请在浏览器中打开开发人员工具并导航到控制台。 Execute the command on console window.scrollTo(0,400)在控制台 window.scrollTo(0,400) 上执行命令在此处输入图片说明

You should add a scroll to the page to select all elements using:您应该使用以下方法向页面添加滚动以选择所有元素:

Selenium.executeScript("window.scrollBy(0,450)", "");

If you have a large list, add the scroll several times through the execution.如果您的列表很大,请在执行过程中多次添加滚动条。 Note the scroll only go to a certain point in the page for example (0, 450) .请注意滚动只会转到页面中的某个点,例如(0, 450)

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

This code works for me.这段代码对我有用。 As the page which I'm testing, loads as we scroll down.作为我正在测试的页面,在我们向下滚动时加载。

Javascript executor always does the job perfectly: Javascript 执行器总是完美地完成这项工作:

((JavascriptExecutor) driver).executeScript("scroll(0,300)");

where (0,300) are the horizontal and vertical distances respectively.其中(0,300)分别是水平和垂直距离。 Put your distances as per your requirements.根据您的要求设置距离。

If you a perfectionist and like to get the exact distance you like to scroll up to on the first attempt, use this tool, MeasureIt .如果您是一个完美主义者并且喜欢在第一次尝试时获得想要向上滚动的确切距离,请使用此工具MeasureIt It's a brilliant firefox add-on.这是一个出色的火狐插件。

Thanks for Ripon Al Wasim's answer.感谢 Ripon Al Wasim 的回答。 I did some improvement.我做了一些改进。 because of network problems, I retry three times until break loop.由于网络问题,我重试了 3 次,直到中断循环。

driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollBy(0,2000)")

    # Wait to load page
    time.sleep(scroll_delay)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")

    if last_height == new_height:
        try_times += 1

    if try_times > 3:
        try_times = 0
        break
    last_height = new_height

JavascriptExecutor is best to scroll down a web page window.scrollTo Function in JavascriptExecutor can do this JavascriptExecutor 最好向下滚动一个网页window.scrollTo JavascriptExecutor 中的函数可以做到这一点

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0,100"); 

Above code will scroll down by 100 y coordinates上面的代码将向下滚动 100 y 坐标

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");

Javascript Javascript

We can scroll to a specific element:我们可以滚动到特定元素:

const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
  1. If you want to scroll the page vertically to perform some action, you can do it using the following JavaScript.如果要垂直滚动页面以执行某些操作,可以使用以下 JavaScript 来完成。 ((JavascriptExecutor)driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”); ((JavascriptExecutor)driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

     Where 'JavascriptExecutor' is an interface, which helps executing JavaScript through Selenium WebDriver. You can use the following code to import.

import org.openqa.selenium.JavascriptExecutor;导入 org.openqa.selenium.JavascriptExecutor;

2.If you want to scroll at a particular element, you need to use the following JavaScript. 2.如果要在特定元素处滚动,则需要使用以下 JavaScript。

WebElement element = driver.findElement(By.xpath(“//input [@id='email']”));((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, element); WebElement element = driver.findElement(By.xpath(“//input [@id='email']”));((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, element) ;

Where 'element' is the locator where you want to scroll.其中“元素”是您要滚动的定位器。

3.If you want to scroll at a particular coordinate, use the following JavaScript. 3.如果要在特定坐标处滚动,请使用以下 JavaScript。
((JavascriptExecutor)driver).executeScript(“window.scrollBy(200,300)”); ((JavascriptExecutor)driver).executeScript(“window.scrollBy(200,300)”); Where '200,300' are the coordinates.其中“200,300”是坐标。

4.If you want to scroll up in a vertical direction, you can use the following JavaScript. 4.如果你想垂直向上滚动,你可以使用下面的JavaScript。 ((JavascriptExecutor) driver).executeScript(“window.scrollTo(document.body.scrollHeight,0)”); ((JavascriptExecutor) driver).executeScript(“window.scrollTo(document.body.scrollHeight,0)”);

  1. If you want to scroll horizontally in the right direction, use the following JavaScript.如果要沿正确方向水平滚动,请使用以下 JavaScript。 ((JavascriptExecutor)driver).executeScript(“window.scrollBy(2000,0)”); ((JavascriptExecutor)driver).executeScript(“window.scrollBy(2000,0)”);

  2. If you want to scroll horizontally in the left direction, use the following JavaScript.如果要向左水平滚动,请使用以下 JavaScript。 ((JavascriptExecutor)driver).executeScript(“window.scrollBy(-2000,0)”); ((JavascriptExecutor)driver).executeScript(“window.scrollBy(-2000,0)”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM