简体   繁体   中英

How to scroll inside a div with Puppeteer?

I want to use Puppeteer to scroll inside a div that has a scrollbar, but where the overall window doesn't have a scrollbar. Let's take for example, the following URL:

https://www.google.com/maps/place/DO+%26+CO+Restaurant+Stephansplatz/@48.2082385,16.3693837,17z/data=!4m7!3m6!1s0x476d079f2c500731:0xed65abfb2c337243!8m2!3d48.2082385!4d16.3715725!9m1!1b1

You can see in the left hand side there are reviews, and the whole section has a scrollbar. A quick inspect element shows that the whole thing is surrounded by a div which has the following classes widget-pane-content scrollable-y . So, I tried to do something like this:

const scrollable_section = 'div.widget-pane-content.scrollable-y';
await page.evaluate((selector) => {
    const scrollableSection = document.querySelector(selector);
    scrollableSection.scrollTop = scrollableSection.offsetHeight;
}, scrollable_section);

But, this didn't work. I also noticed that one clicks the space button, if it is focused inside the reviews section, it also scrolls down automatically. So, I also tried to do something like this:

await page.focus(scrollable_section);
await page.keyboard.press('Space');

But, this also didn't seem to work. Any ideas how can I scroll inside a div with Puppeteer?

First of all, you are using the wrong selector, and you are using : instead of = in your const declaration.

This line of code should actually be:

const scrollable_section = '.section-listbox .section-listbox';

Additionally, since the content in this section is dynamically loaded, you should wait for this element to contain content before attempting to scroll down:

await page.waitForSelector('.section-listbox .section-listbox > .section-listbox');

As a result, your final code should look like this:

const scrollable_section = '.section-listbox .section-listbox';

await page.waitForSelector('.section-listbox .section-listbox > .section-listbox');

await page.evaluate(selector => {
  const scrollableSection = document.querySelector(selector);

  scrollableSection.scrollTop = scrollableSection.offsetHeight;
}, scrollable_section);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM