首页 > 解决方案 > 使用 PhantomJS 访问 URL 时出现 403 Forbidden

问题描述

如果我在 Chrome 中访问以下网页,它会正常加载:https ://www.cruisemapper.com/?poi=39

但是,当我运行以下 PhantomJS 脚本时,它只是转到相同的 URL 并将整个 DOM 字符串输出到控制台,我收到 403 Forbidden 消息:

var page = require('webpage').create(),
    url = 'https://www.cruisemapper.com/?poi=39';

page.open(url, function (status) {
    if (status === 'success') {
        console.log(page.evaluate(function () {
            return document.documentElement.outerHTML;
        }));

        phantom.exit();
    }
});

这是控制台的确切输出:

<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /
on this server.<br>
</p>

</body></html>

我认为如果我添加某种用户代理字符串,它可能会起作用。因此,我在 console.log 行上方添加了以下内容:

page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36';

但这没有用。所以我尝试了以下方法:

page.customHeaders = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
};

但这也没有用。有没有人对我如何访问上面的 URL 而不收到 403 Forbidden 消息有任何建议?谢谢你。

标签: phantomjsuser-agenthttp-status-code-403

解决方案


您的代码对我来说很好(不过我建议使用视口大小仿真,请参阅代码)。如果您仍然收到 403,请尝试更改您的 IP,这可能是该站点现在对您开放(您可能多次访问该页面)。

var page = require('webpage').create(),
    url = 'https://www.cruisemapper.com/?poi=39';

page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36';

page.viewportSize = { width: 1440, height: 900 }; // <-- otherwise it's 400x300 by default

// It's good to watch for errors on the page
page.onError = function (msg, trace) 
{
    console.log(msg);
    trace.forEach(function(item) {
        console.log(' ', item.file, ':', item.line);
    })
}

page.open(url, function (status) {

    console.log(status);
    page.render("page.png"); // Also useful to check if you get what you expect

    if (status === 'success') {
        console.log(page.evaluate(function () {
            return document.documentElement.outerHTML;
        }));

        phantom.exit();
    }
});

推荐阅读