page.includeJs()
将 jQuery 注入到页面中,因此只能从页面上下文(在page.evaluate()
)。页面上下文是沙盒的,因此您无法调用phantom.exit()
来自页面上下文,因为没有这样的对象window.phantom
.
您有两种可能使其发挥作用。
阻止 AJAX
jQuery.ajax()
接受一个async: false
属性来进行阻塞 AJAX 调用,因此您可以简单地进行调用,然后以迭代方式继续执行。
page.open(url, function (status) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function () {
console.log("Solve Captcha");
page.evaluate(function(){
$.ajax({
async: false, // this
url: 'http://localhost/captcha.php',
data: { filename: 'C:\\wamp\\www\\images\\0.png' },
type: 'post',
success: function (output) {
console.log('Solved');
},
});
});
phantom.exit();
});
});
等待完成
waitFor https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js示例中的可用于等待设置特定条件。该条件应设置在success
AJAX 调用的回调:
page.open(url, function (status) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function () {
console.log("Solve Captcha");
page.evaluate(function(){
window._finishedCall = false;
$.ajax({
url: 'http://localhost/captcha.php',
data: { filename: 'C:\\wamp\\www\\images\\0.png' },
type: 'post',
success: function (output) {
console.log('Solved');
window._finishedCall = true;
},
});
});
waitFor(function check(){
return page.evaluate(function(){
return window._finishedCall;
});
}, function onReady(){
phantom.exit();
}, 10000); // 10 seconds maximum timeout
});
});
第二个问题是你想要进行跨域请求,因为captcha.php
在本地主机上并且url
与本地主机不同。你需要运行 PhantomJS--web-security=false
选项并使用完全限定的 URL:http://localhost/captcha.php
.