Joh*_*ith 0 javascript node.js puppeteer
假设我有一个 500 像素宽的元素,称为“选择器”。例如,我将如何点击像素 400?
根据 puppeteer 文档, .hover() 将悬停在元素的中间。当我使用类似的代码对其进行测试时
const selector = await page.$('selector');
await selector.hover();
await selector.click();
Run Code Online (Sandbox Code Playgroud)
果然,它点击了像素 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);
}
})();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5688 次 |
最近记录: |