PhantomJs:如何停止重定向到另一个URL并加载原始URL

PhantomJs: How to stop redirecting to another URL and load original URL

本文关键字:URL 加载 原始 另一个 何停止 重定向 PhantomJs      更新时间:2023-09-26

我试图使用PhantomJs从forbes.com加载此URL

'http://www.forbes.com/sites/prossermarc/2016/10/14/softbanks-new-100b-tech-fund-shows-exactly-how-its-expanding-beyond-telco/#6e5027484acb'

但这是重定向到http://www.forbes.com/forbes/welcome/,所以我不能抓住我想要的页面的标题。

我尝试中止请求,如果重定向URL是http://www.forbes.com/forbes/welcome/,但完全停止页面加载和phantomjs失败。

page.onResourceRequested = function(requestData, networkRequest) {
 if (requestData.url.split('?')[0] === 'http://www.forbes.com/forbes/welcome/') {
     networkRequest.abort();
 }
};

我是否可以停止此重定向并加载原始URL?

我是否可以停止此重定向并加载原始URL?

是,尝试设置一个不同的用户代理:

page.settings.userAgent = "myAppBot"; // or simply 'bot'.

福布斯没有重定向机器人,我猜它只向普通的浏览器用户代理显示广告。

我是否可以停止此重定向并加载原始URL?

不,因为它是在服务器级完成的(头重定向)。

但是你可以点击"继续阅读文章"按钮,或者等待forbes.com在5秒左右自动重定向到文章。

我将展示如何等待:

var page = require('webpage').create();
page.viewportSize = { width: 1440, height: 900 };
page.settings.userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
// This callback is run every time a page is done loading.
// The first time it is the welcome page, the second time it's the target page.    
page.onLoadFinished = function(){
    // Let's get the URL of current page
    var url = page.evaluate(function(){
        return document.location.href;
    });
    console.log(url);
    // Is it the welcome page? No
    if(url.indexOf("forbes/welcome") == -1)
    {
        setTimeout(function(){
            page.render("forbes-article.png");
            var title = page.evaluate(function(){
                return document.querySelector("h1.article-headline").innerText;
            });
            console.log(title);
            phantom.exit();
        }, 1000);
    }
    // Yes it is the welcome page, let's just wait
    else
    {
        console.log("redirected to welcome screen, waiting");
        page.render("forbes-welcome.png");
    }
};
page.open("http://www.forbes.com/sites/prossermarc/2016/10/14/softbanks-new-100b-tech-fund-shows-exactly-how-its-expanding-beyond-telco/#6e5027484acb");