Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use phantomJS to simulate mouse hover on a HTML element

I have the phantomJS code below to fetch the HTML code:

var page = require('webpage').create();
var url = 'http://example.com/';

page.open(url, function (status) {
    var js = page.evaluate(function () {
        return document;
    });
    console.log(js.all[0].outerHTML); 
    phantom.exit();
});

The content I want to fetch will only be read while the mouse is hover on the specific element which is controlled by JavaScript, so the code above is not working.

I want to know how to simulate the mouse hover on a HTML element using the phantomJS code. Let's say I want to mouse hover over on a element then dump the HTML to output, how should I do?

Edit: The following code didn't work. What could be the problem?

var page = require('webpage').create();
var url = 'http://example.com/';

page.open(url, function (status) {
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function(){
        $('#some_element').trigger('hover');
    });
    var js = page.evaluate(function () {
        return document;
    });
    console.log(js.all[0].outerHTML); 
    phantom.exit();
}); 
like image 362
Marcus Thornton Avatar asked Jun 04 '13 10:06

Marcus Thornton


1 Answers

Try load your page with jquery:

page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
    //(...)
});

and then call hover on your element:

$('#some_element').trigger('hover');
like image 187
Lukasz Koziara Avatar answered Oct 22 '22 13:10

Lukasz Koziara