【问题标题】:How to get elements in headless browser inside a bounding box如何在边界框内的无头浏览器中获取元素
【发布时间】:2016-09-01 04:53:03
【问题描述】:

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

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

【问题讨论】:

  • PhantomJS 或 CasperJS 没有特定的功能来做到这一点,所以这实际上是一个正常的 JavaScript 问题。我相信已经有答案了。另外,PhantomJS 和 CasperJS 与 Selenium 或 Webdriver 协议无关

标签: javascript dom phantomjs casperjs


【解决方案1】:

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

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 返回一个调整为当前滚动位置的矩形。因此,给定的矩形会根据当前滚动位置进行调整,以便在同一坐标系中进行比较。

请注意,无法将 DOM 元素从页面上下文(casper.evaluate 内部)返回到外部。您将不得不在内部使用这些元素并仅返回该数据的可序列化表示。您可以在casper.evaluate 中使用普通的console.log 调用,但您必须注册到"remote.message" 事件才能看到它们。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2015-12-08
    • 2018-06-24
    • 2014-08-23
    • 2017-08-25
    相关资源
    最近更新 更多