PhantomJS .click() not working

2019-05-01 14:58发布

问题:

This code does not work:

var page = require('webpage').create();

page.open('http://www.ebay.com/', function() {
    console.log('Page loaded');
    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
        console.log('jQuery included');
        page.render('C:/beforeclick.jpeg');
        console.log('Render 1');
        page.evaluate(function() {
            $('.btn-prim').click();
        });
        page.render('C:/afterclick.jpeg');
        console.log('Render 2');
    });
});

In fact $('.btn-prim').click() does not work, beforeclick.jpeg and afterclick.jpeg are the same. In browser console $('.btn-prim').click() works fine. Ebay here just for example, it does not work on other sites too. Please help me to solve the problem, I am novice in JavaScript.

回答1:

This will give you a proper solution to the situation

page.evaluate(function(){
    var a = document.getElementById("target_element_to_be_clicked");
    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);
});

Hope this helps



回答2:

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