How to send click event to div or button using PhantomJS (1.9.8)?

I don't understand how to close a modal or element with PhanthomJS using sendEvent()

.

For example, I tried to do it using the code below, or by using CaperJS click

and clickLabel

many others, but it does not work.

var webpage = require('webpage').create();
var url  = 'http://sourceforge.net/';
webpage.viewportSize = { width: 1280, height: 800 };
webpage.render("test1.png");

webpage.onLoadFinished = function(status) {
    var coords = webpage.evaluate(function() {
        var firstLink = document.querySelector('a.btn');
        return {
            x: firstLink.offsetLeft,
            y: firstLink.offsetTop
        };
    });
    console.log(coords.x);
    console.log(coords.y);
    webpage.sendEvent('mousedown', coords.x, coords.y ,'left');
};


webpage.open(url,function(){
    webpage.render("test2.png");
    phantom.exit()
});

      

Here's an element I would like to skip. enter image description here

+3


source to share


1 answer


offsetLeft

and offsetTop

only give the offset based on the parent element. You would have to sum all the offsets of the elements up to the root node. This is at least what CasperJS does.

If this notification is static, you can define the coordinates once and use them every time. Based on the screenshot (444,330) seems like a good replacement for coords.x, coords.y

.

You can also just use a synchronized mouse click as described here , which is what CasperJS does, but in conjunction with a specific position. This is a simple synthetic click:



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

      


Also, you have two callbacks ( onLoadFinished

and a function in webpage.open

) to load the page. You should only have one, so you don't run into problems when one of them is called. After you click, it's best to wait a little setTimeout

and let the page change before taking a screenshot.

+2


source







All Articles