gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:38:39 41 4
gpt4 key购买 nike

我一直试图弄清楚如何在 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/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com