更新:请参见下面的编辑
我不认为
PhantomJS无法处理该页面
很可能是我们没有好好模拟真实浏览器。
快速搜索“instagram登录phantomjs”找到了这个神奇的解决方案,可行:https://github.com/awener/instagram-login-phantomjs/blob/master/phan.js
它使用PhantomJS模拟“真实”按键和点击的机制。
以下是脚本副本,以备不时之需。
var page = require('webpage').create();
var username = "myusername";
var password = "password";
page.viewportSize = { width: 1024 , height: 600 };
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';
page.open('https:/instagram.com/accounts/login/', function() {
var ig = page.evaluate(function() {
function getCoords(box) {
return {
x: box.left,
y: box.top
};
}
function getPosition(type, name) {
var input = document.getElementsByTagName(type);
for(var i = 0; i < input.length; i++) {
if(name && input[i].name == name) return getCoords(input[i].getBoundingClientRect());
else if(!name && input[i].className) return getCoords(input[i].getBoundingClientRect());
}
}
return {
user: getPosition('input', 'username'),
pass: getPosition('input', 'password'),
login: getPosition('button')
};
});
page.sendEvent('click',ig.user.x, ig.user.y);
page.sendEvent('keypress', username);
page.sendEvent('click',ig.pass.x, ig.pass.y);
page.sendEvent('keypress', password);
page.sendEvent('click', ig.login.x, ig.login.y);
setTimeout(function() {
page.render('/path/to/screenshot.png');
phantom.exit();
}, 5000);
});
编辑并解释如何在Linux上运行脚本
这个在Debian/Ubuntu上没有工作的原因是SSL证书问题。
当你使用--debug=true命令行选项运行时,有一个详细模式可以告诉你PhantomJS正在做什么。使用它,我找到了问题的原因:
[DEBUG] Network - SSL Error: "The issuer certificate of a locally looked up certificate could not be found"
[DEBUG] Network - SSL Error: "The root CA certificate is not trusted for this purpose"
[DEBUG] Network - Resource request error: QNetworkReply::NetworkError(SslHandshakeFailedError) ( "SSL handshake failed" ) URL: "https://instagramstatic-a.akamaihd.net/h1/scripts/polyfills/es5-sham.min.js/fc3c22cf2d67.js"
...
为避免这种问题,您只需在运行Phantomjs时添加另一个CLI参数,告诉它忽略SSL错误:
/pth/to/phantomjs --ignore-ssl-errors=true /path/to/script.js
page.render
方法内指定保存图像的目录。例如:page.render('/home/ritik/instagram.png');
或者page.render('C:\\Users\\Ritik\\instagram.png');
。 - Vaviloff