Callombert
Callombert

Reputation: 1099

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:

http://www.buddytv.com/trivia/game-of-thrones-trivia.aspx

Here's the code:

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

  click('a[href="javascript:___gid_10(0)"]');
  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.

Upvotes: 2

Views: 8147

Answers (3)

Yuval A.
Yuval A.

Reputation: 6089

You can also use PhantomJS's sendEvent to simulate a mouse-click, documentation here:

http://phantomjs.org/api/webpage/method/send-event.html

Upvotes: 0

PP.
PP.

Reputation: 10864

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.

Upvotes: 3

sajay
sajay

Reputation: 315

Try this

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

Upvotes: 0

Related Questions