Desplácese hacia arriba o hacia abajo en Selenium WebDriver (Selenium 2) usando java


He escrito el siguiente código en Selenium 1 (también conocido como Selenium RC) para el desplazamiento de páginas usando java:

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

¿Cuál es el código equivalente en Selenium 2 (WebDriver)?

Author: Ripon Al Wasim, 2012-09-06

12 answers

Para Desplácese hacia abajo:

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

O, puedes hacer lo siguiente:

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

Para Desplácese hacia arriba:

jse.executeScript("window.scrollBy(0,-250)", "");
OR,
jse.executeScript("scroll(0, -250);");
 84
Author: Ripon Al Wasim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-05 11:48:57

Desplazarse hasta la parte inferior de una página:

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
 31
Author: user3472488,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 12:03:18

Esto puede no ser una respuesta exacta a su pregunta (en términos de WebDriver), pero he encontrado que la biblioteca java.awt es más estable que selenium.Keys. Por lo tanto, una acción de página abajo usando el primero será:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
 9
Author: rs79,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-04 17:26:10

Hay muchas maneras de desplazarse hacia arriba y hacia abajo en Selenium Webdriver Siempre uso Java Script para hacer lo mismo.

A continuación está el código que siempre funciona para mí si quiero desplazarme hacia arriba o hacia abajo

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

Puede obtener el código completo desde aquí Página de desplazamiento en Selenio

Si desea desplazarse por un elemento, a continuación, la pieza de código funcionará para usted.

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

Obtendrá el documento completo aquí Desplácese para el elemento específico

 9
Author: Mukesh Otwani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 20:52:43
JavascriptExecutor js = ((JavascriptExecutor) driver);

Desplácese hacia abajo:

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

Desplácese hacia arriba:

js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");
 2
Author: CreaThor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-28 09:22:20

No quería usar JavaScript, ni ninguna librería externa, así que esta era mi solución (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();

También puede hacer de este un método de extensión para desplazarse hacia arriba o hacia abajo en cualquier elemento.

 1
Author: KthProg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 18:30:26

Prueba esto

        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=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=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);
        }
 0
Author: Maddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-27 02:39:09

Debe agregar un desplazamiento a la página para seleccionar todos los elementos usando Selenium.executeScript("window.scrollBy(0,450)", "").

Si tiene una lista grande, agregue el scroll varias veces durante la ejecución. Tenga en cuenta que el desplazamiento solo va a un cierto punto de la página, por ejemplo (0,450).

 0
Author: SufiWorld,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-24 17:12:34
JavascriptExecutor jse = ((JavascriptExecutor) driver);
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Este código funciona para mí. Como la página que estoy probando, se carga mientras nos desplazamos hacia abajo.

 0
Author: Latha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 09:11:12

Javascript executor siempre hace el trabajo perfectamente:

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

Donde (0,300) son las distancias horizontales y verticales respectivamente. Ponga sus distancias según sus requisitos.

Si eres un perfeccionista y te gusta obtener la distancia exacta a la que te gusta desplazarte en el primer intento, usa esta herramienta, MeasureIt. Es un complemento brillante para Firefox.

 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-10 14:59:36

Gracias por la respuesta de Ripon Al Wasim. Hice algunas mejoras. debido a problemas de red, reintento tres veces hasta romper el bucle.

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
 0
Author: Ivan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 10:55:51
  1. Si desea desplazarse por la página verticalmente para realizar alguna acción, puede hacerlo utilizando el siguiente JavaScript. ((JavascriptExecutor)driver).executeScript ("window.scrollTo (0, documento.cuerpo.Altura de desplazamiento)");

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

Importar org.openqa.selenio.En el caso de que se trate de un]}

2.Si desea desplazarse a un elemento en particular, debe usar el siguiente JavaScript.

Elemento WebElement = controlador.findElement (By.xpath ("//input [@id = 'email']")); ((JavascriptExecutor) controlador).executeScript ("argumentos [0].scrollIntoView ();", elemento);

Donde 'element' es el localizador donde desea desplazarse.

3.Si desea desplazarse por una coordenada en particular, utilice el siguiente JavaScript.
((JavascriptExecutor) driver).executeScript ("window.Desplazamiento (200.300)"); Donde '200,300' son las coordenadas.

4.Si desea desplazarse hacia arriba en dirección vertical, puede utilizar el siguiente JavaScript. ((JavascriptExecutor) controlador).executeScript ("window.scrollTo (documento.cuerpo.Altura de desplazamiento,0)");

  1. Si desea desplazarse horizontalmente en la dirección correcta, utilice el siguiente JavaScript. ((JavascriptExecutor)driver).executeScript ("window.scrollBy(2000,0)");

  2. Si desea desplazarse horizontalmente en la dirección izquierda, utilice lo siguiente JavaScript. ((JavascriptExecutor)driver).executeScript ("window.scrollBy(-2000,0)");

 0
Author: Tapan Khimani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 06:52:21