PhantomJs脚本中的Ajax请求
问题: phantomJs脚本中的Ajax请求到本地页面不起作用(没有响应)
问题:如何使其工作? 任何想法或可能的解决方案
描述:我正在运行一个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
位于localhost中,而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
from示例可用于等待设置特定条件。 应在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
。