javascript - 如何在 PhantomJS 中转到下一页进行抓取

标签 javascript web-scraping phantomjs

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

代码如下:

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();
});

您可以自己尝试以了解所有这些是如何工作的。

最佳答案

通过将 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);
}

请注意,除了静态超时之外,还有更多方法可以等待。相反,您可以

关于javascript - 如何在 PhantomJS 中转到下一页进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32979753/

相关文章:

javascript - javascript 中的变量行为,使用 += 运算符时旧值不会被覆盖

javascript - PhantomJS:将 Javascript 添加到网页(不是 PhantomJS 环境)

java - 在java程序中执行phantomjs脚本

用于生成 javascript 的 .NET 库?

javascript - 用户在删除按钮中传递选定的选项值 : React

python - 如何将每个 Scrapy 蜘蛛项目与另一个 Scrapy 蜘蛛项目进行比较?

python - 抓取多个页面时经常出现 HTTP 错误 413

python - django 动态蜘蛛错误 "check_mandatory_vars"

java - 我需要 ghostdriver 才能在 java 中使用 selenium 和 phantomjs 吗?

javascript - 将 Typescript 2 @Types 与 typescript 1.8.10 一起使用