如何使用 Puppeteer 在 div 内滚动? [英] How to scroll inside a div with Puppeteer?

查看:89
本文介绍了如何使用 Puppeteer 在 div 内滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Puppeteer 在具有滚动条但整个窗口没有滚动条的 div 内滚动.我们以以下 URL 为例:

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,1837,3693/data=!4m7!3m6!1s0x476d079f2c500731:0xed65abfb2c337243!8m2!3d48.2082385!4d16.3715725!9m1!1b1

您可以在左侧看到评论,并且整个部分都有一个滚动条.快速检查元素显示整个事物被一个 div 包围,该 div 具有以下类 widget-pane-content scrollable-y.所以,我尝试做这样的事情:

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');

但是,这似乎也不起作用.任何想法如何使用 Puppeteer 在 div 内滚动?

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

推荐答案

首先,您使用了错误的选择器,您使用的是 : 而不是 =在您的 const 声明中.

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);

这篇关于如何使用 Puppeteer 在 div 内滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆