Click on a link with phantom.js and retrieve the document html
ajax, javascript, jquery, phantomjs
Solution
I finally managed to achieve my task with this code. I skipped the click action and went directly to the AJAX call:
// phantomjs test.js 'http://www.example.com' 'anID'
var system = require('system');
var page = require('webpage').create();
var url = system.args[1];
var target = system.args[2];
page.onConsoleMessage = function (msg) {
console.log(msg);
phantom.exit();
};
page.open(url, function (status) {
function evaluate(page, func) {
var args = [].slice.call(arguments, 2);
var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
return page.evaluate(fn);
}
page.injectJs('jquery-1.7.2.min.js');
if (status === 'success') {
evaluate(page, function(target) {
$.ajax({
type: 'POST',
url: document.URL,
data: "__EVENTTARGET=" + target,
success: function(msg){
console.log(msg);
}
});
}, target);
}
});
Problem
I'm new with phantom.js and I'm trying to navigate on a website page, to click on a link (that calls an AJAX function and changes the document HTML) with phantom.js. Here is my code: ``` window.setTimeout(function(){ phantom.exit(); }, 120000); var page = require('webpage').create(); page.open("http://example.com", function(status) { if (status !== 'success') { console.log('{"error":"Unable to load the address for page"}'); phantom.exit(); } var action = page.evaluate(function() { document.getElementById("anID").click(); return "clicked"; }); var results = page.evaluate(function() { return document.documentElement.innerHTML; }); console.log(action); window.setInterval(function() { console.log(results); phantom.exit(); }, 3000); }); ``` I'm very confusing as in my "action" function, the click() call is raising that error repeated 3 times: TypeError: 'undefined' is not a function phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1 ph.js:121 null TypeError: 'undefined' is not a function phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1 ph.js:121 null TypeError: 'undefined' is not a function phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1 ph.js:121 null Also, if I comment the line when I send a click, the action function does not raise an error anymore and returns well the "clicked" console log. But 3 times... What am I doing wrong ? Thanks in advance.