The aim for my PhantomJS script is to load a specific website, find the search input element, write text in that input and perform the search. From the page loaded containing the search results I just want to grab the whole URL - it will contain the search parameters.
After the interaction with the input, I'm using onUrlChanged()
to detect when the search results URL has returned. This never gets called. I don't know whether it is due to the search not being completed or whether the onUrlChanged()
is in the wrong place.
var page = require('webpage').create(),
response = {};
page.onUrlChanged = function(targetUrl) { // Page loaded
page.evaluate(function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase().indexOf('search') > -1) {
inputs[i].value = 'cat dog';
inputs[i].focus();
page.sendEvent('keypress', 'Enter');
break;
}
}
});
// This does not get called
page.onUrlChanged = function(targetUrl) { // Search result loaded
response.content = targetUrl;
console.log(JSON.stringify(response));
phantom.exit(1);
};
};
page.open('http://www.mysearch.com/', function(status) {
if (status !== 'success') {
response.content = 'Unable to access network';
console.log(JSON.stringify(response));
phantom.exit(1);
} else {
phantom.exit(1);
}
});
Note: I know that CasperJS is better at this kind of use case, however in my current environment I have to use PhantomJS.