Ajax 在 PhantomJs 脚本中请求

Ajax request in PhantomJs script

问题: Ajax 在 phantomJs 脚本中对本地页面的请求不起作用(无响应)

问题:我怎样才能让它工作?有什么想法或可能的解决方案吗?

描述:我是运行一个phantomJs脚本,我需要访问另一个页面中php函数提供的一些数据(当地的)。为此,我在 phantomjs 脚本中对该页面使用 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");
        $.ajax({
            url: 'captcha.php',
            data: { filename: 'C:\wamp\www\images\0.png' },
            type: 'post',
            success: function (output) {
                console.log('Solved');
                phantom.exit();
            },
        });
    });
});

php 页面位于本地 WAMP 服务器中,并且已经使用 ajax(在 phantomJs 脚本之外)进行了测试,并且工作正常。脚本和 php 文件位于文件夹 C:\wamp\www 中,而图像 0.png 位于子文件夹 C:\wamp\www\images 中。

重要提示:页面captcha.php在本地,而phantomJs请求的页面不是本地,也就是说,page.open 打开一个非本地的 url

我不明白为什么在 phantomJs 脚本中发出此请求不起作用。你能帮帮我吗?

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 可用于等待设置特定条件。此条件应在 AJAX 调用的 success 回调中设置:

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在localhost上,url和localhost不同。您需要使用 --web-security=false 选项 运行 PhantomJS 并使用完全限定的 URL:http://localhost/captcha.php.