admin管理员组

文章数量:1320616

I would like to get elements query selector by passing x,y coordinates.

Or maybe few elements that satisfy the coordinates.

Maybe I can do mouse.click(x, y) and then get clicked element but I don't want page to take any actions just get the query of the element.

Is there possibility to do that?

I would like to get elements query selector by passing x,y coordinates.

Or maybe few elements that satisfy the coordinates.

Maybe I can do mouse.click(x, y) and then get clicked element but I don't want page to take any actions just get the query of the element.

Is there possibility to do that?

Share Improve this question edited Feb 21, 2019 at 9:31 ROKIKOKI asked Feb 20, 2019 at 13:09 ROKIKOKIROKIKOKI 6212 gold badges11 silver badges28 bronze badges 1
  • Possible duplicate of Retrieve the position (X,Y) of an HTML element – Seblor Commented Feb 20, 2019 at 13:30
Add a ment  | 

2 Answers 2

Reset to default 6

If you just need a topmost element by viewport coordinates, you can try DocumentOrShadowRoot.elementFromPoint(). If you need to pose a unique selector, you can try to process element array from the DocumentOrShadowRoot.elementsFromPoint() (add more checks to the example below — classes, ids, attributes, children count and order etc.):

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto('https://example/');

    console.log(await page.evaluate(() => {
      return document.elementFromPoint(100, 100).tagName;
    }));

    console.log(await page.evaluate(() => {
      return document.elementsFromPoint(100, 100)
                     .map(({ tagName }) => tagName).reverse().join(' > ');
    }));

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();
DIV
HTML > BODY > DIV

You have to consider first that you might get many elements on the same position, including the main HTML element.

First, you need to get all the elements:

Array.prototype.slice.call(document.getElementsByTagName("*"))

Then, we now that each element has a function called getClientRects, which will return an array of "boxes".

Based on that, we can filter all the elements having one box in the coordinate you need:

var x = 150;
var y = 1250;
Array.prototype.slice.call(document.getElementsByTagName("*")).filter(e =>
     Array.prototype.slice.call(e.getClientRects()).find(rect => 
         rect.top <= x && rect.bottom >= x && rect.left <= y && rect.right >= y))

You could do something like that in your evaluate call in Puppeteer.

本文标签: javascript(Puppeteer) Is there a way to get element query by xyStack Overflow