如何在Phantomjs中获取多个链接并关注这些链接?

时间:2013-10-16 10:06:35

标签: web-scraping phantomjs casperjs

我是Phantomjs的初学者这么多问题我无法解决他们的问题。你介意帮我解决这个问题吗?我有关于通过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
...

这意味着我想获得此网址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?你能帮助我吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

尝试就像这样,它应该工作。当然我假设,parent数组正确填充了正确的链接。

var child = page.evaluate(function() {
    return [].map.call(document.querySelectorAll('div.productRow'), function(div) {
        return div.innerHTML;
    });
});
相关问题