如何在木偶操纵者中使用x/y坐标点击元素? [英] How to click element using x/y coordinates with puppeteer?

查看:28
本文介绍了如何在木偶操纵者中使用x/y坐标点击元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试如何使用木偶操纵器中的x和y坐标单击页面上的按钮,但我一直无法使其正常工作。这就是我当前使用的。

await page.mouse.click(x, y, {button: 'left'})

没有出现错误,只是没有单击任何元素。所以我猜我没有找到正确的位置。

我使用的是Pupeteer中的默认视口,即800px x 600px。这就是我要手动尝试定位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();
})();

这篇关于如何在木偶操纵者中使用x/y坐标点击元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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