0

我是 Phantomjs 的初学者,有很多问题我自己无法解决。你介意帮我解决这个问题吗?我有关于通过 Phantomjs 获取多动态 url 的问题。

例子:

-- 我的 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?你能帮助我吗?谢谢你的帮助。

4

1 回答 1

0

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

var child = page.evaluate(function() {
    return [].map.call(document.querySelectorAll('div.productRow'), function(div) {
        return div.innerHTML;
    });
});
于 2014-07-04T05:59:37.957 回答