如何点击元素木偶的特定部分 [英] How to click on specific part of element puppeteer

查看:47
本文介绍了如何点击元素木偶的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 500 像素宽的元素,称为选择器".例如,我将如何点击像素 400?

Say I have an element that's 500 pixels wide, called 'selector'. How would I go about, for example, clicking on pixel 400?

根据 puppeteer 文档,.hover() 将悬停在元素的中间.当我使用

According to the puppeteer docs, .hover() will hover over the middle of the element. And when I tested it using code like

const selector = await page.$('selector');
await selector.hover();
await selector.click();

果然,它点击了像素 250.很明显,代码存在来实现这一点.我查看了 puppeteer 文档,但找不到我需要的源代码.有人可以帮忙吗?

sure enough, it clicked right on pixel 250. So clearly, the code exists to make this happen. I looked through the puppeteer docs, but couldn't find the source code I needed. Can anyone help?

推荐答案

Puppeteer 提供了一种点击页面上特定像素的方法 (Mouse.click(x, y)).您可以计算相对于元素位置的位置:

Puppeteer provides a method to click on a specific pixel on the page (Mouse.click(x, y)). You could calculate where that is relative to your element's position:

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

这篇关于如何点击元素木偶的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆