0

我正在使用 casperJS 和 slimerJS 引擎来获取由 ajax 响应加载的视频。

脚步

  1. 获取网址列表
  2. 对列表中的每个 url 递归调用 casper.open
  3. 每个casper.open调用都需要等待前面的casper.open发送一个 ajax 响应。

前两点效果很好。我对第三个有问题。重要的是要了解我不需要等待页面完成加载才能加载下一个casper.open。我只需要等待来自每个 url 的一个 ajax 响应。当我收到此回复时,我可以关闭此网址并打开下一个。

为此,递归循环从第一次出现开始。然后,使用 resource.received 事件监听网络并等待特殊的 contentType。这个 contentType 给了我响应,我可以在其中找到加载视频的 url。我将此 url 存储在一个数组中,并且可以关闭 thise casper.open并开始下一个。

这是我的代码:

// Some JS code...

function receiver(resource) {
    if (resource.contentType == 'myContentType') {
        sources.push(resource.url);// When catch good conteType, push in sources array
    }
}
casper.on("resource.received", receiver); // Listen responses

// Some JS code...

// Login below
casper.then(function() {
    this.evaluate(function(username, password) {
        document.querySelector('#username').value = username;
        document.querySelector('#password').value = password;
        document.querySelector('#LoginSend').click();
    }, username, password);
});

casper.then(function() {
    this.wait(1000, function() {
        this.waitFor(function() {
            urls = this.evaluate(function() {
                //Get and return all urls
            });
            return true;
        });
    });
});

casper.then(function() {
    this.wait(1000, function() {
        click_link();
    });
});

function click_link() {
    casper.then(function() {
        this.wait(1000, function() {
            this.open(address + urls[i]);// Open new url, i tried with theOpen, don't work too.
            this.waitFor(function() {
                return !!sources[i]; // Wait for the contentType is catch
            }, function() {
                sources.pop(); // Because resource.received has two staged
                this.wait(2000, function() {
                    // Until we don't go to all url, recursive call
                    if (sources.length < urls.length) {
                        i++;
                        click_link();
                    }
                });
            });
        });

    });
}

// Some JS code...

问题是第一个casper.open打开页面,等待捕获好的 contentType 并将好的 url 存储在我的数组源中。然后,下一个casper.open被调用,程序永远处于等待状态。这是因为 contentType 永远不会被捕获......但它与上一个页面是同一类型的页面。如果我先从第二页开始,它会起作用。只有递归循环的下一次出现不起作用,第一次出现无关紧要。
此外,如果我在浏览器(chrome 或 firefox)中打开这些页面,它工作得很好,他抓住了 contentType。所以,问题来自我的程序。
在 resource.received 侦听器期间有时我会出错:“错误类型 $.cookie”。但即使我有 jquery.cookie.js,它也不起作用。

我试图关闭页面或存储 cookie 并清除每个casper.open之间的页面,但它仍然无法正常工作。

先感谢您。

4

0 回答 0