如何使用PhantomJS(1.9.8)将点击事件发送到div或按钮?

时间:2014-12-20 14:34:06

标签: javascript phantomjs

我不了解如何使用sendEvent()使用PhanthomJS关闭模态或元素。

例如,我尝试使用下面的代码或使用CaperJS clickclickLabel以及许多其他内容来执行此操作,但它无效。

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

这是我想跳过的元素。 enter image description here

1 个答案:

答案 0 :(得分:2)

offsetLeftoffsetTop仅根据父元素提供偏移量。您必须将所有元素偏移量相加到根节点。这至少是CasperJS的作用。

如果此通知是静态的,您可以确定一次坐标并每次都使用它们。基于屏幕截图(444,330)似乎可以替代coords.x, coords.y

您也可以简单地使用here所描述的合成鼠标点击,这是CasperJS所做的,但与特定位置相结合。这是一个简单的合成点击:

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

此外,您在页面加载时有两个回调(onLoadFinishedwebpage.open中的函数)。你应该只有一个,所以当你的一个被调用时,你不会遇到问题。点击后,最好等一下setTimeout,然后在截取屏幕截图之前更改页面。