如何使用 mouse.wheel 在 puppeteer 5.1.0 中向右滚动?

Ste*_*aum 5 node.js puppeteer

我在这个页面上有一个网格。最后一列位于屏幕右侧。我想读取标题单元格文本。我在https://pptr.dev/#?product=Puppeteer&version=v5.1.0&show=api-class-mouse看到了这个片段

所以我在 cucumber/puppeteer 中运行了下面的代码。没有错误,但浏览器中没有任何反应。那么我如何使用此功能或任何其他方式向右滚动。

我无法使用 querySelector... 获取标题,因为选择器在列可见之前不存在。请指教。

async function scrollRight() {
   await this.page.mouse.wheel({ deltaX: 2500 })
}
Run Code Online (Sandbox Code Playgroud)

the*_*ton 4

您的scrollRight()函数应该有一个部分,其中鼠标悬停在右列上。在链接的示例中,也page.mouse.move(x,y)应该适用于您的情况。

要获取列的 XY 坐标,您可以使用elementHandle.boundingBoxpuppeteer 函数。通过一个简单的公式,您可以将光标精确定位到列的中心。

例如:

async function scrollRight() {
  const elem = await page.$('.last-column');
  const boundingBox = await elem.boundingBox();
  await page.mouse.move(
    boundingBox.x + boundingBox.width / 2, // x
    boundingBox.y + boundingBox.height / 2 // y
  );

 await page.mouse.wheel({ deltaX: 2500 });
}
Run Code Online (Sandbox Code Playgroud)

要检查列的可见性,您可以使用page.waitForSelectorvisible: true选项,该选项等待元素可见,即不具有display: noneCSSvisibility: hidden属性。它默认为false,因此如果它在您的用例中导致问题,导致它不可见,它可能会有所帮助。

await page.waitForSelector('.last-column', {
  visible: true,
});
Run Code Online (Sandbox Code Playgroud)