首页 > 解决方案 > PhantomJS 获取特定元素的位置数组

问题描述

我想使用 phantomjs 获取页面上特定标签的位置。例如对于<a>我想得到这个数组的标签:

[
   {
       tag: "a",
       x: 12,
       y: 32,
       width: 100,
       height: 30
   },
   ...
]

我写了这段代码:

page.open(url, function(status){
   ....
   ....
   var a_tags = page.evaluate(function() {
                     return document.getElementsByTagName('a');
                });

   for(index in a_tags){
      console.log(a_tags[index].getBoundingClientRect());
   }
   ....
   ....
})

但是此代码返回错误:

TypeError: null is not a function (evaluating 'a_tags[index].getBoundingClientRect()')

如何使用 phantomjs 从页面获取这些信息,我的代码有什么问题?

标签: javascriptphantomjs

解决方案


我找到了解决方案:

var a_tags = page.evaluate(function() {
      var tags = document.getElementsByTagName('a');
      var res = [];
      for(var index = 0 ; index < tags.length ; index++) {
          var element = tags[index];
          var rect = element.getBoundingClientRect();
          if(rect.left == 0 && rect.top ==0 || rect.width ==0 && rect.height ==0){
                     continue;
          }
          res.push({
                tag: "a",
                rect: rect,
          });
      }
      return res;
});

推荐阅读