2

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.

Callombert
  • 1,099
  • 14
  • 38
  • A string is being passed into the click method, not an actual element, so dispatchEvent is being called on a string, not an element on the page. You'll need to get a reference to the element somehow to make it work. – Douglas Mar 03 '16 at 12:26

3 Answers3

3

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.

PP.
  • 10,764
  • 7
  • 45
  • 59
  • PP. is there any way to determine "how much" should we wait? – Sali Hoo Nov 15 '13 at 14:50
  • Unfortunately the shorter you wait the more CPU you use in loops - and PhantomJS does use a reasonable amount of CPU. I would think 250ms is adequate as humans wouldn't respond much quicker than that. – PP. Nov 16 '13 at 08:54
0

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);
    }
sajay
  • 295
  • 1
  • 2
  • 11
0

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

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

Yuval A.
  • 5,849
  • 11
  • 51
  • 63