如何配置Poltergeist或PhantomJS不遵循重定向? [英] How to configure Poltergeist or PhantomJS to not follow redirects?

查看:123
本文介绍了如何配置Poltergeist或PhantomJS不遵循重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了一些测试,这些测试要求JS驱动程序不遵循重定向.是否可以配置Poltergeist来做到这一点?

I have some tests that require the JS driver to not follow redirects. Is it possible to configure Poltergeist to do this?

我注意到可以使用命令行界面将命令传递给PhantomJS ,那么也许这是另一种方式?

I noticed that it is possible to pass commands to PhantomJS using the Command Line Interface, so perhaps that is another way of doing this?

推荐答案

我不熟悉Poltergeist,所以我只想回答有关PhantomJS的问题.

I'm not familiar with Poltergeist, so I'm only going to answer about PhantomJS.

您所需要做的就是两个事件处理程序 page.onResourceRequested page.onResourceReceived . HTTP重定向会同时产生HTTP请求和HTTP响应,因此在收到重定向响应时将调用处理程序.然后,您可以将重定向URL添加到数组中,并在实际发送重定向请求时,可以检测并停止它.

All you need for this are the two event handlers page.onResourceRequested and page.onResourceReceived. An HTTP redirect produces both a HTTP request and HTTP response on so the handlers are called when the redirect response is received. You can then add the redirect URL to an array and when the redirect request is actually send, you can detect and stop it.

var redirectURLs = [],
    doLog = true;

page.onResourceRequested = function(requestData, networkRequest) {
    if (doLog) console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData) + "\n");
    if (redirectURLs.indexOf(requestData.url) !== -1) {
        // this is a redirect url
        networkRequest.abort();
    }
};

page.onResourceReceived = function(response) {
    if (doLog) console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response) + "\n");
    if (response.status >= 300 && response.status < 400 && response.redirectURL) { // maybe more specific
        redirectURLs.push(response.redirectURL);
    }
};

这仅适用于HTTP重定向.还有其他类型的重定向需要其他解决方案.例如HTML重定向或JavaScript重定向.

This only works for HTTP redirects. There are other types of redirects that need other solutions. For example HTML redirects or JavaScript redirects.

这篇关于如何配置Poltergeist或PhantomJS不遵循重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆