Triggering click event PhantomJS

百般思念 提交于 2019-12-14 02:02:34

问题


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.


回答1:


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.




回答2:


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);
    }



回答3:


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

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



来源:https://stackoverflow.com/questions/17468611/triggering-click-event-phantomjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!