javascript - 如何使用 puppeteer 的 x/y 坐标单击元素?

标签 javascript node.js puppeteer

我一直试图弄清楚如何在 puppeteer 中使用 x 和 y 坐标单击页面上的按钮,但我无法让它工作。这是我目前正在使用的。await page.mouse.click(x, y, {button: 'left'})没有错误发生,它根本没有点击任何元素。所以我的猜测是我没有正确找到它的位置。
我在 puppeteer 中使用默认视口(viewport),即 800 像素 x 600 像素。这就是我正在做的手动尝试并在 DOM 中找到按钮的 x 和 y 的方法。

document.getElementsByClassName("classname")[0].getBoundingClientRect().x
> 90.125

document.getElementsByClassName("classname")[0].getBoundingClientRect().y
> 128
所以我将它添加到点击事件中。await page.mouse.click(90.125 , 128, {button: 'left'})什么也没有发生。我究竟做错了什么?

最佳答案

您可以找到 iframe 及其坐标,然后在此 iframe 中添加所需元素的偏移量,然后单击:

const puppeteer = require("puppeteer");
 
(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
 
  await page.goto("https://example.com/page_with_frame", {waitUntil: 'networkidle0'});
 
  // Find the iframe
  const frame = await page.waitForSelector("iframe");
  // Find its coordinates
  const rect = await page.evaluate(el => {
    const {x, y} = el.getBoundingClientRect();
    return {x, y};
  }, frame);
 
  // Values found manually by doing 
  // `document.querySelector('.yscp_link').getBoundingClientRect()`
  // in the dev console. Add 5 to them, because it's the top left corner
  const offset = {x: 213 + 5, y: 11 + 5};
 
  // Click
  await page.mouse.click(rect.x + offset.x, rect.y + offset.y);
 
  await frame.waitForNavigation({
    waitUntil: 'networkidle2',
  });
 
  await page.screenshot({ path: "example.png" });
 
  await browser.close();
})();

关于javascript - 如何使用 puppeteer 的 x/y 坐标单击元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65311714/

相关文章:

javascript - 如何在 JavaScript 中访问 Chrome 拼写检查建议

javascript - 如何从另一个文件触发子进程代码?

javascript - 查找并替换 Json 文件中的项目

javascript - 在 Puppeteer 中获取 elementHandle 的兄弟

javascript - Puppeteer - 向下滚动,直到你不能再

php - json转php代码,需要功能完善

javascript - Bootstrap Datepicker 显示的月份数

node.js - 使用 node.js amqp 模块时如何将 AQMP 消息缓冲区转换为 JSON 对象?

javascript - 丢失全局变量值

dart - 使用 puppeteer 获取源 html