What is the Puppeteer API method to scroll the page?
Antek N
antek n profile pic

In Puppeteer, a Node.js library for controlling headless Chrome or Chromium browsers, you can scroll the page using thepage.evaluate() method along with JavaScript code to manipulate the scrolling behavior. Here is a long-form answer that explains the process in detail: 1. Scrolling the page usingpage.evaluate():

1
2
3
4
5

   await page.evaluate(() => {
     window.scrollBy(0, window.innerHeight);
   });
   

This code usespage.evaluate() to execute a JavaScript function within the context of the browser page. In this case, the function utilizes thewindow.scrollBy() method to scroll the page vertically by the height of the viewport (window.innerHeight). ThescrollBy() method takes two parameters: the horizontal and vertical scrolling amounts. By setting the horizontal amount to0 and the vertical amount towindow.innerHeight, we scroll the page vertically by one viewport height. If you want to scroll horizontally, you can modify thescrollBy() method accordingly:

1
2
3
4

   window.scrollBy(window.innerWidth, 0); // Scrolls right by one viewport width
   window.scrollBy(-window.innerWidth, 0); // Scrolls left by one viewport width
   

2. Scrolling to a specific element on the page: If you want to scroll to a specific element on the page, you can use thescrollIntoView() method. Here's an example:

1
2
3
4
5
6

   const element = await page.$('your-selector');
   await page.evaluate((el) => {
     el.scrollIntoView();
   }, element);
   

In this code snippet,page.$('your-selector') uses the$ function to find the element on the page based on the provided selector. Then, thescrollIntoView() method is called on the found element usingpage.evaluate(), which scrolls the page to ensure the element is visible. Alternatively, you can scroll to an element using its coordinates:

1
2
3
4
5
6

   await page.evaluate(() => {
     const element = document.querySelector('your-selector');
     element.scrollIntoView();
   });
   

3. Smooth scrolling: By default, scrolling using the methods mentioned above is instantaneous. However, if you prefer smooth scrolling animation, you can use thescrollTo() method with thebehavior option set to'smooth':

1
2
3
4
5
6
7
8
9

   await page.evaluate(() => {
     window.scrollTo({
       top: 0,
       left: 0,
       behavior: 'smooth'
     });
   });
   

In this example, thescrollTo() method is used to scroll to the top-left corner of the page with a smooth animation. You can adjust thetop andleft values to scroll to specific coordinates on the page. These methods allow you to scroll the page and navigate to specific elements using Puppeteer. You can customize the scrolling behavior based on your requirements, whether it's scrolling by a fixed amount, scrolling to an element, or achieving smooth scrolling animations.