【问题标题】:How to double click in Puppeteer如何在 Puppeteer 中双击
【发布时间】:2021-01-30 16:43:21
【问题描述】:

我有一个工作区,可以在其中添加不同的对象。有一种场景,双击后,可以在工作区中自动添加一个对象。我经历了不同的解决方案,但没有一个真正奏效。

这是我尝试过的:

await page.evaluate(selector => {
  var targLink = document.querySelector(selector);
  var clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent('dblclick', true, true);
  targLink.dispatchEvent(clickEvent);
}, selector)

【问题讨论】:

    标签: javascript puppeteer playwright


    【解决方案1】:

    您可以使用mouse.click(x, y[, options])


    首先获取xy

    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);
    

    然后通过clickCount作为选项来模拟双击。

    await page.mouse.click(rect.x, rect.y, { clickCount: 2 });
    

    完整代码:

    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();
    })();
    

    更新

    您可以使用delay 选项在两次点击之间添加延迟。下面的代码会以 100 毫秒的延迟双击元素。

    await page.mouse.click(rect.x, rect.y, { clickCount: 2, delay: 100 });
    

    【讨论】:

    • 它会双击,但它的速度不像真人,这就是为什么它没有触发所需的双击,最终不会在工作区中添加对象。
    • 您可以使用延迟,例如await page.mouse.click(rect.x, rect.y, { clickCount: 2, delay: 100 });。在两次点击之间等待 100 毫秒
    • 谢谢你,它让我朝着正确的方向前进,但事实证明这不会产生两次点击。这将创建一个单击,该单击注册为 clickCount: 2 的单击。因此,要实际执行双击,我们需要调用 page.mouse.click 两次:一次使用 clickCount: 1,一次使用 clickCount: 2 和延迟: 100
    猜你喜欢
    • 2019-12-26
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2018-12-25
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多