Anustart Anustart - 1 year ago 197
Javascript Question

Triggering click event PhantomJS

I'm using PhantomJS to try and scrape a trivia question and its answer. With help from Stackoverflow. I have little understanding of Javascript so please explain what I'm doing wrong in details
The page is there:

Here's the code:

function click(el) {
var ev = document.createEvent("MouseEvent");
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null

answer = page.evaluate(function() {

return $('body').html();

I'm trying to click on the first answer and return whatever the page returns after that (except it's returning NULL). Any help appreciated! Thanks.


FAQ: why doesn't the page change instantly once I've dispatched my event?

After you click you need to use window.setTimeout to check the changes made to the page some time afterwards. Say a second. Or 5. Because pages don't instantly change. They take time to load and render.

I want to plaster this answer all over the front page of the PhantomJS website.

FAQ: I want to dispatch an event on my page. How?

Well - you have to do the dispatch from within the page.evaluate() call. Otherwise you're just dispatching an event on PhantomJS itself. Which is pointless.