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
2 Answers
Reset to default 6If 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
版权声明:本文标题:javascript - (Puppeteer) Is there a way to get element query by x, y? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742070709a2419106.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论