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:
.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.
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./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.
Share Improve this question asked Jul 4, 2013 at 11:02 CallombertCallombert 1,09914 silver badges38 bronze badges 1- 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 Commented Mar 3, 2016 at 12:26
3 Answers
Reset to default 3FAQ: 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.
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);
}
You can also use PhantomJS's sendEvent
to simulate a mouse-click, documentation here:
http://phantomjs/api/webpage/method/send-event.html