How to scroll down a webpage in selenium using…
We can scroll down a webpage in Selenium using Java. Selenium is unable to handle scrolling directly. It takes the help of the Javascript Executor to perform the scrolling action up to an element.
First of all, we have to locate the element up to which we have to scroll. Next, we shall use the Javascript Executor to run the Javascript commands. The method executeScript is used to run Javascript commands in Selenium. We shall take the help of the scrollIntoView method in Javascript and pass true as an argument to the method.
Syntax −
WebElement elm = driver.findElement(By.name("name")); ((JavascriptExecutor) driver) .executeScript("arguments[0].scrollIntoView(true);", elm);
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ScrollAction{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); //launch application driver.get ("https://www.tutorialspoint.com/about/about_careers.htm "); // identify element WebElement n=driver.findElement(By.xpath("//*[text()='Contact']")); // Javascript executor ((JavascriptExecutor)driver) .executeScript("arguments[0].scrollIntoView(true);", n); } }
2 COMMENTS
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?