Sam*_*mad 1 javascript puppeteer playwright
我有一个工作区,可以在其中添加不同的对象。有一种场景,双击时可以在工作区中自动添加一个对象。我尝试过不同的解决方案,但没有一个真正有效。
这是我尝试过的:
await page.evaluate(selector => {
var targLink = document.querySelector(selector);
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('dblclick', true, true);
targLink.dispatchEvent(clickEvent);
}, selector)
Run Code Online (Sandbox Code Playgroud)
您可以使用mouse.click(x, y[, options])。
首先得到x和y。
const selector = "#elementID";
const rect = await page.evaluate((selector) => {
const element = document.querySelector(selector);
if (!element) return null;
const { x, y } = element.getBoundingClientRect();
return { x, y };
}, selector);
Run Code Online (Sandbox Code Playgroud)
然后clickCount作为选项传递以模拟双击。
await page.mouse.click(rect.x, rect.y, { clickCount: 2 });
Run Code Online (Sandbox Code Playgroud)
完整代码:
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://www.example.com", {
waitUntil: "domcontentloaded",
});
const selector = "#elementID";
const rect = await page.evaluate((selector) => {
const element = document.querySelector(selector);
if (!element) return null;
const { x, y } = element.getBoundingClientRect();
return { x, y };
}, selector);
if (rect) {
await page.mouse.click(rect.x, rect.y, { clickCount: 2 });
} else {
console.error("Element Not Found");
}
await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)
更新
您可以使用delay选项在两次单击之间添加延迟。下面的代码将双击元素,延迟 100 毫秒。
await page.mouse.click(rect.x, rect.y, { clickCount: 2, delay: 100 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7693 次 |
| 最近记录: |