- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Scroll Down or UP a Page in Selenium Webdriver?
We can scroll down or up a page in Selenium webdriver using JavaScript Executor. Selenium can execute JavaScript commands with the help of the executeScript method.
To scroll down vertically in a page we have to use the JavaScript command window.scrollBy. Then pass the pixel values to be traversed along the x and y axis for horizontal and vertical scroll respectively.
The positive value set for x-axis shall scroll the page to the right while the negative value for x-axis shall scroll it to the left. Similarly, the positive value set for y-axis shall scroll down the page while the negative value for y-axis shall scroll up the page.
Syntax
JavascriptExecutor j = (JavascriptExecutor)driver; j.executeScript("window.scrollBy(0,500)"); j.executeScript("window.scrollBy(0,-500)");
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 ScrollUpDown{ 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(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); // scroll down by 500 pixels with Javascript Executor JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("window.scrollBy(0,500)"); // identify element WebElement m = driver.findElement(By.linkText("Latest Courses")); String s = m.getText(); System.out.println("Text obtained on scrolling down: "+ s); // scroll down up 500 pixels with Javascript Executor j.executeScript("window.scrollBy(0,-500)"); // identify element WebElement n = driver.findElement(By.tagName("h4")); String r = n.getText(); System.out.println("Text obtained on scrolling up: "+ r); driver.quit(); } }
Output
Advertisements