如何在PhantomJS中进行下一页的抓取

时间:2015-10-06 21:06:02

标签: javascript web-scraping phantomjs

我试图从一个有多个页面的网站上获取几个元素。我目前正在使用PhantomJS来完成这项工作,我的代码几乎可以正常工作,但问题是我的代码在第一页上擦了两次,即使(根据日志)我似乎已经转移到第二页了。 / p>

以下是代码:

var page = require('webpage').create();
page.viewportSize = { width: 1061, height: 1000 }; //To specify the window size
page.open("website", function () {

    function fetch_names(){
        var name = page.evaluate(function () {
            return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){
                return name.getAttribute('href');
            });
        });
        console.log(name.join('\n'));
        page.render('1.png');
        window.setTimeout(function (){
            goto_next_page();
        }, 5000);
    }

    function goto_next_page(){
        page.evaluate(function () {
            var a = document.querySelector('#block-system-main .next a');
            var e = document.createEvent('MouseEvents');
            e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            waitforload = true;

        });
        fetch_names();
    }

    fetch_names();
});

您可以自己尝试一下,了解所有这些工作原理。

1 个答案:

答案 0 :(得分:3)

您需要等待点击后加载页面,而不是在点击之前将setTimeout()fetch_names移至goto_next_page

function fetch_names(){
    var name = page.evaluate(function () {
        return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){
            return name.getAttribute('href');
        });
    });
    console.log(name.join('\n'));
    page.render('1.png');
    goto_next_page();
}

function goto_next_page(){
    page.evaluate(function () {
        var a = document.querySelector('#block-system-main .next a');
        var e = document.createEvent('MouseEvents');
        e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(e);
        waitforload = true;

    });
    window.setTimeout(function (){
        fetch_names();
    }, 5000);
}

请注意,还有很多方法可以等待除静态超时之外的其他内容。相反,你可以