简体   繁体   English

如何在无边框浏览器中的边界框内获取元素

[英]How to get elements in headless browser inside a bounding box

I have a use case where I need the user to mark a bounding box on a web page and using PhantomJS or CasperJS I would like to get the elements that are covered or touched by this box. 我有一个用例,我需要用户在网页上标记一个边界框,并使用PhantomJS或CasperJS来获取此框覆盖或触摸的元素。

Is that doable and if so how? 这样可行吗?

It is fairly easy to iterate over all elements of the page, get their bounding box and see if that bounding box is inside of the given box: 遍历页面的所有元素,获取其边界框并查看该边界框是否在给定框内是相当容易的:

var rectExample = {
  top: 0,
  left: 0,
  width: 500,
  height: 100
};
casper.evaluate(function(rect) {
  rect.top -= window.scrollY;
  rect.left -= window.scrollX;
  var all = document.querySelectorAll('*');
  var filtered = Array.prototype.filter.call(all, function (el) {
    var elRect = el.getBoundingClientRect();
    return elRect.width > 0
      && elRect.height > 0
      && rect.width >= elRect.width 
      && rect.height >= elRect.height 
      && rect.top <= elRect.top 
      && rect.left <= elRect.left 
      && (rect.top + rect.height) >= (elRect.top + elRect.height) 
      && (rect.left + rect.width) >= (elRect.left + elRect.width);
  });

  filtered.forEach(function(el){
    // TODO: do something with the element that is inside of the rectangle
  });
}, rectExample);

Note that getBoundingClientRect returns a rectangle adjusted to the current scroll position. 请注意, getBoundingClientRect返回一个调整为当前滚动位置的矩形。 Therefore the given rectangle is adjusted by the current scroll position in order to make the comparisons in the same coordinate system. 因此,给定的矩形由当前滚动位置调整,以便在同一坐标系中进行比较。

Note that it is not possible to return DOM elements from the page context (inside of casper.evaluate ) to the outside. 请注意,不可能将DOM元素从页面上下文(在casper.evaluate内部)返回到外部。 You will have to work with those elements inside and return only a serializable representation of that data. 您将必须在内部使用这些元素,并且仅返回该数据的可序列化表示。 You can use normal console.log calls inside of casper.evaluate , but you have to register to the "remote.message" event in order to see them. 您可以在casper.evaluate内部使用普通的console.log调用,但是必须注册到"remote.message"事件才能看到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM