假设我有一个 500 像素宽的元素,称为“选择器”。例如,我该如何点击像素 400?
根据 puppeteer 文档,.hover() 将悬停在元素的中间。当我使用像
这样的代码测试它时const selector = await page.$('selector');
await selector.hover();
await selector.click();
果然,它点击了第 250 像素。很明显,代码的存在就是为了实现这一点。我查看了 puppeteer 文档,但找不到我需要的源代码。有人可以帮忙吗?
最佳答案
Puppeteer 提供了一种单击页面上特定像素的方法 ( Mouse.click(x, y)
)。您可以计算相对于元素位置的位置:
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("http://yoursite.com");
const elem = await page.$("#my-element");
await clickOnElement(elem, 400);
await page.screenshot({ path: "example.png" });
await browser.close();
// Clicks on an element at position x,y
async function clickOnElement(elem, x = null, y = null) {
const rect = await page.evaluate(el => {
const { top, left, width, height } = el.getBoundingClientRect();
return { top, left, width, height };
}, elem);
// Use given position or default to center
const _x = x !== null ? x : rect.width / 2;
const _y = y !== null ? y : rect.height / 2;
await page.mouse.click(rect.left + _x, rect.top + _y);
}
})();
关于javascript - 如何点击 element puppeteer 的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60254145/