When automating web applications, scrolling to the top or bottom of a page can be essential, especially for triggering lazy loading, infinite scroll, or ensuring certain elements are in view. In this guide, we'll walk through how to scroll both up and down using Playwright, one of the most reliable tools for browser automation.
Why Scrolling Matters in Browser Automation?
Modern web pages often load content dynamically as users scroll. Whether you're testing user experience, capturing data, or interacting with hidden elements, controlling scroll behavior is crucial.
How to Scroll to the Bottom of the Page
You can scroll to the bottom using JavaScript execution or by simulating a mouse wheel scroll.
JavaScript Scroll
// Scroll to the bottom await page.evaluate(() => { window.scrollTo(0, document.body.scrollHeight); });
Mouse Wheel Scroll
page.mouse().wheel(0, 10000); // Scrolls down 10,000 pixels
Scroll using Keyboard
// Press the End key to scroll to the bottom page.keyboard().press("End");
Scroll Until End (Infinite Scroll Example)
const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch({ headless: false }); const page = await browser.newPage(); await page.goto('https://example.com'); // Replace with your target URL let previousHeight = await page.evaluate(() => document.body.scrollHeight); while (true) { // Scroll down await page.mouse.wheel(0, 1000); await page.waitForTimeout(1000); // wait for content to load // Measure new scroll height const newHeight = await page.evaluate(() => document.body.scrollHeight); // Break loop if no new content was loaded if (newHeight === previousHeight) { break; } previousHeight = newHeight; } console.log('Reached the bottom of the page.'); await browser.close(); })();
How to Scroll to the Top of the Page
JavaScript Scroll
// Scroll to the top of the page await page.evaluate(() => { window.scrollTo(0, 0); // Scroll to the top (0,0 position) });
Mouse Wheel Scroll
// Scroll to the top using the mouse wheel await page.mouse.wheel(0, -10000); // This simulates a large scroll up
No comments:
Post a Comment