vol*_*olt 7 javascript phantomjs
我正在尝试使用phantom.js登录instagram网站.我的第一个方法是:
document.querySelector("input[name='username']").value = "Username";
document.querySelector("input[name='password']").value = "Pass";
Run Code Online (Sandbox Code Playgroud)
但是这段代码不会改变da DOM.
我的第二种方法:
document.getElementsByClassName("_kp5f7 _qy55y")[0].setAttribute("value", "Username");
document.getElementsByClassName("_kp5f7 _qy55y")[0].value = "Pass";
Run Code Online (Sandbox Code Playgroud)
但是当我检查网络包字段时,用户名和密码都是空白的.
Instagram登录页面:https://www.instagram.com/accounts/login/
更新:请参阅下面的编辑答案
我真的不这么认为
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) {
// find fields to fill
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()); // this is for login button
}
}
return {
user: getPosition('input', 'username'),
pass: getPosition('input', 'password'),
login: getPosition('button')
};
});
// fill in data and press login
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);
// wait for response
setTimeout(function() {
page.render('/path/to/screenshot.png');
phantom.exit();
}, 5000);
});
Run Code Online (Sandbox Code Playgroud)
编辑有关如何在Linux上运行脚本的说明
这在Debian/Ubuntu上不起作用的原因是SSL证书问题.
当您使用--debug = true CLI选项运行它时,有一个详细的模式告诉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"
...
Run Code Online (Sandbox Code Playgroud)
要避免此类问题,您只需使用另一个CLI参数运行Phantomjs,告知它忽略SSL错误:
/pth/to/phantomjs --ignore-ssl-errors=true /path/to/script.js
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2587 次 |
| 最近记录: |