2013-10-16 4 views
0

나는 Phantomjs에서 초보자이므로 많은 문제를 해결할 수 없다. 이 문제를 해결하도록 도와 주시겠습니까? Phantomjs가 다중 동적 URL을 가져 오는 문제가 있습니다.다중 링크를 얻고 Phantomjs에서이 링크를 따라 가려면 어떻게해야합니까?

예 : -

내 index.html을은 다음과 같습니다

<!DOCTYPE html> 
<html> 
<body> 
<h1>Homepage</h1> 
<ul> 
    <li><a href="laptop.html">Laptop</a></li> 
    <li><a href="tablet.html">Tablet</a></li> 
</ul> 
</body> 
</html> 

- 내 laptop.html 파일 (동일로 tablet.html 파일)입니다 :

<!DOCTYPE html> 
<html> 
<body> 
<h1>Laptop Page</h1> 
<div class="productRow">Product of Laptop 1</div> 
<div class="productRow">Product of Laptop 2</div> 
</body> 
</html> 

다음과 같이 인쇄하고 싶습니다.

Category Name: Laptop 
Product: Product of Laptop 1 
Product: Product of Laptop 2 
.... 

Category Name: Tablet 
Product: Product of Tablet 1 
Product: Product of Tablet 2 
... 

그것은이 URL의 내용을 얻고 싶다는 뜻입니다 http://abc.com/test/. 그러면 나는 (UL LI A HREF)의 링크를 얻을 것이다. 그런 다음 해당 링크를 따라 콘텐츠의 하위 페이지를 자동으로 가져옵니다.

이 Phantomjs에 의해 내 샘플 코드입니다 :

var page = require('webpage').create(); 
var url = 'http://localhost/test'; 

page.open(url, function() { 
    //Get parent link 
    var parent = page.evaluate(function() { 
     var test = document.querySelectorAll('li a'); 
     return Array.prototype.map.call(test, function(elem) { 
      return elem.href;  
     }); 
    }); 
    for(var i=0; i < parent.length; i++){ 
     //Print parent link 
     console.log("Parent link:" + parent[i]); 

     //Then open child link   
     page.open(parent[i],function(){   
      //console.log(document.title);   
      var child = page.evaluate(function() { 
       var test = document.querySelectorAll('div.productRow'); 
       return Array.prototype.map.call(test, function(elem) { 
        return elem.innerHTML;  
       }); 
      }); 
      console.log(child.length); 
      phantom.exit(); 
     }); 

    } 

}); 

이유 CONSOLE.LOG (child.length) = 0? 나 좀 도와 줄 수있어? 당신의 도움을 주셔서 감사합니다.

+0

여기에 파이썬 코드가 있습니까? –

답변

0

다음과 같이 시도해보십시오. 작동해야합니다. 물론 parent 어레이가 올바른 링크로 올바르게 채워져 있다고 가정합니다.

var child = page.evaluate(function() { 
    return [].map.call(document.querySelectorAll('div.productRow'), function(div) { 
     return div.innerHTML; 
    }); 
}); 
관련 문제