非常接近,现在将您的两个片段合并为一个。page.open()
是异步的,这就是为什么您需要在第一个页面完成后才打开下一个页面:
var page = require('webpage').create();
var url = "http://www.example.com";
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
page.open(url, function (status) {
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
page.evaluate(function() {
document.getElementById("email").value = "email";
document.getElementById("pass").value = "password";
document.getElementById("u_0_1").click();
// page is redirecting.
});
setTimeout(function () {
page.evaluate(function () {
console.log('haha');
});
page.render("example.png");
var url = "http://www.google.com";
page.open(url, function (status) {
setTimeout(function () {
page.evaluate(function () {
console.log('haha');
});
page.render("google.png");
phantom.exit();
}, 5000);
});
}, 5000);
});
为了真正看到console.log()
代替page.evaluate()
您需要注册到page.onConsoleMessage http://phantomjs.org/api/webpage/handler/on-console-message.html事件。还有更多其他事件在调试时很有帮助。
不要忘记将协议(http:// 或 file:///)添加到您要打开的 URL。 PhantomJS 在这方面有点挑剔。
而不是等待一段静态时间(setTimeout()
)直到您执行某些操作后加载下一页。您应该利用page.onLoadFinished
事件。对于导航密集型脚本来说,这是相当麻烦的。使用CasperJS http://casperjs.org/对于更长的脚本。
很多时候Element.click()
不起作用。这个问题 https://stackoverflow.com/questions/15739263/phantomjs-click-an-element对于这些情况有很多解决方案。