Home  >  Article  >  Java  >  How to scroll down using Selenium WebDriver in Java?

How to scroll down using Selenium WebDriver in Java?

WBOY
WBOYforward
2023-08-20 16:41:281165browse

We can use Selenium to scroll down. Selenium cannot handle scrolling operations directly. It needs to use Javascript Executor to perform scrolling operations until it scrolls to the specified element.

First, we need to locate the element we want to scroll to. Next, we will use Javascript Executor to run Javascript commands. In Selenium, use the executeScript method to run Javascript commands. We will take the help of the scrollIntoView method in Javascript and pass true as a parameter to the method. The Chinese translation of

Grammar

WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",elm);

Example

is:

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm ");
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView
      (true);", n);
   }
}

Output

如何使用Java中的Selenium WebDriver向下滚动?

The above is the detailed content of How to scroll down using Selenium WebDriver in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete