phantomjs发送点击事件

时间:2014-04-18 12:09:40

标签: javascript phantomjs

我有以下脚本:

var page = require('webpage').create();
var fs=require('fs');
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';
page.open('http://www.google.com/ncr', function() {
    page.viewportSize = { width: 1920, height: 1080 };
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        var text = page.evaluate(function() {
            return document.getElementById('gb_70').href;
        });
        console.log(text);
        var point = page.evaluate(function() {
            var element = document.getElementById('gb_70');
            var rect = element.getBoundingClientRect();
                return {
                x:rect.left + Math.floor(rect.width / 2), y:rect.top + Math.floor(rect.height / 2)
                };
        });
        page.sendEvent('click', point.x, point.y);
        console.log(point);
        console.log(point.x);
        console.log(point.y);
        page.clipRect = {top:point.x, left:point.y, height:15, width:15};
        page.render('captureelement.png');

        page.clipRect = {top:33, left:1854, height:15, width:15};
        page.render('captureaiureadetest.png');

        page.clipRect = {top:0, left:0, height: 0, width: 0};


    console.log("Trecut");  
    fs.write('Log.html', page.content , 'w');
    fs.write('Log.txt', text , 'w');
    page.render('capturefinal.png');
    phantom.exit()
    });
});

它没有捕获元素,它没有点击它,但获取坐标并且不会向我发送任何错误。

我是phantomjs的新手,请有人告诉我它是什么问题。

节日快乐。

2 个答案:

答案 0 :(得分:0)

我在以下地址找到了这个例子:' http://newspaint.wordpress.com/2013/03/19/how-to-click-on-a-div-or-span-using-phantomjs/'并为我工作。见下面的例子:

var element = document.getElementById('gb_70');
var e = document.createEvent("MouseEvents");

// If you need pass the clientX, clientY, etc., you can call
// initMouseEvent instead of initEvent
e.initEvent.apply(e, ['mouseover', true, true]);

element.dispatchEvent(e);

答案 1 :(得分:0)

希望以下方法有用。它在版本1.9中适用于我

page.evaluate(function(){
    var a = document.getElementById("ELEMENT_ON_WHICH_CLICK_TO_BE_DONE");
    var e = document.createEvent('MouseEvents');
    e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
    waitforload = true;
});

这对我有用。希望这能帮助你解决问题