phantomjs - 使用 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 消息有任何建议?谢谢你。
解决方案
您的代码对我来说很好(不过我建议使用视口大小仿真,请参阅代码)。如果您仍然收到 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();
}
});
推荐阅读
- c# - 如何将方法“utilities.DecryptStringFromBase64String”的调用限制为一次
- tensorflow - Tensorflow 在 Eager Execution 模式下循环切片分配给变量
- java - 如何防止 Eclipse 中出现流利的资源泄漏警告?
- arrays - 在日期 SwiftUI 上对映射数组进行排序
- php - PHP 7.3 - count(NULL) 使 php 脚本超时
- c# - Windows 服务执行我的所有代码 OnStart() 但在引发异常对象未设置实例之后
- reactjs - Ant Forms:为什么值不同需要解释?
- android - 如何用另一个活动的片段替换片段?
- javascript - 滚动事件上的@keyframe 动画
- javascript - 显示视频或图像,具体取决于有效的