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

How to get elements in headless browser inside a bounding box

我有一个用例,我需要用户在网页上标记一个边界框,并使用 PhantomJS 或 CasperJS 我想获取被该框覆盖或触摸的元素。

这可行吗?如果可行,怎么做?

遍历页面的所有元素、获取它们的边界框并查看该边界框是否在给定框内是相当容易的:

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

请注意,getBoundingClientRect return 是一个调整到当前滚动位置的矩形。因此,给定的矩形根据当前滚动位置进行调整,以便在同一坐标系中进行比较。

请注意,无法将页面上下文(casper.evaluate 内部)中的 return DOM 元素传送到外部。您将不得不处理内部的这些元素,并且 return 只是该数据的可序列化表示。您可以在 casper.evaluate 中使用正常的 console.log 调用,但您必须注册到 "remote.message" 事件才能看到它们。