【发布时间】:2020-02-04 22:51:25
【问题描述】:
我使用 PhantomJS 登录并从中抓取表格的网站最近更新了,新版本似乎需要在用户名和密码字段上实际发生按键才能登录。
我的旧代码如下所示:
var page = require('webpage').create();
phantom.cookiesEnabled = true;
page.open("https://website.location.com/log", function(status) {
if (status === "success") {
page.evaluate(function() {
document.getElementsByName("username")[0].value = "uname";
document.getElementsByName("password")[0].value = "pass12";
document.getElementsByTagName("button")[0].click();
});
window.setTimeout(function() {
page.render("page.png");
page.open("https://website.location.com/log/#!/activity/search", function(status) {
window.setTimeout(function() {
page.render("profil.png");
console.log(page.content);
phantom.exit();
}, 5000);
});
}, 5000);
}
});
旧代码与旧登录页面和 console.log 正确输出到调用此 phantomjs 代码的脚本的效果很好,但现在我不确定从这里去哪里。我已经尝试以几种不同的方式使用 page.sendEvent('keypress',page.event.key.U) ,但是任何时候我插入那个位似乎都会冻结。当我加载页面时,光标会自动在正确的字段中,否则我认为使用 tab 应该切换到下一个字段并输入将能够输入我的数据。
我尝试过的示例
var page = require('webpage').create();
phantom.cookiesEnabled = true;
page.open("https://website.location.com/log", function(status) {
if (status === "success") {
page.evaluate(function() {
page.sendEvent('keypress', page.event.key.U);
page.sendEvent('keypress', page.event.key.N);
page.sendEvent('keypress', page.event.key.A);
page.sendEvent('keypress', page.event.key.M);
page.sendEvent('keypress', page.event.key.E);
page.sendEvent('keypress', page.event.key.Tab);
page.sendEvent('keypress', page.event.key.P);
page.sendEvent('keypress', page.event.key.A);
page.sendEvent('keypress', page.event.key.S);
page.sendEvent('keypress', page.event.key.S);
page.sendEvent('keypress', page.event.key.1);
page.sendEvent('keypress', page.event.key.2);
document.getElementsByTagName("button")[0].click();
});
window.setTimeout(function() {
page.render("page.png");
page.open("https://website.location.com/log/#!/activity/search", function(status) {
window.setTimeout(function() {
page.render("search.png");
console.log(page.content);
phantom.exit();
}, 5000);
});
}, 5000);
}
});
我也尝试了一些类似的变体,但似乎并没有更好:
page.sendEvent('keypress', "uname");
page.sendEvent('keypress', page.event.key.Tab);
page.sendEvent('keypress', "pass12");
page.sendEvent('keypress', page.event.key.Enter);
【问题讨论】:
-
您确定发送“tab”事件会切换到另一个输入吗?它可能会向事件处理系统发送“tab”键盘事件并绕过浏览器行为。也许尝试另一种方式来改变输入焦点,也许通过点击密码输入。
-
选项卡实际上工作正常。您的评论确实帮助我找到了一条页面渲染路径,以了解在哪个阶段发生了什么,所以您确实提供了帮助。如果您好奇我是如何解决这个问题的,请参阅我发布的答案。
标签: javascript authentication phantomjs