Cannot click an item using Phantomjs

From a message: How to flag A directive in a PhantomJS test I understand that I need to create my own function to click an element, but how can I use it?

The following code gives me an error TypeError: 'undefined' is not a function (evaluating 'click(obj)')

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

page.open(url, function(status) {
    page.evaluate(function() {
        var obj = document.querySelectorAll('button')[0];
        click(obj);
    });
    console.log(page.content);
    phantom.exit();
});


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);
}
+4
source share
3 answers

I understood the problem. A click bypassed the javascript site. Fortunately, PhantomJS has a sendEvent function that dispatches an event just like a real user:

var rect = page.evaluate(function() {
    return $('a.whatever')[0].getBoundingClientRect();
});
page.sendEvent('click', rect.left + rect.width / 2, rect.top + rect.height / 2);

Found above solution through PhantomJS; click item

+1
source

PhantomJS . , page.evaluate(), DOM . click() document, .

page.evaluate() , , . , ( , ).

page.open(url, function(status) {
    page.evaluate(function() {
        if (typeof window.click !== "function") {
            window.click = function(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);
            }
        }
        var obj = document.querySelectorAll('button')[0];
        click(obj);
    });
    console.log(page.content);
    phantom.exit();
});

:

+4
    page.evaluate(function () {
        document.getElementById("login").click();
    });

... , ?

0

Source: https://habr.com/ru/post/1612278/


All Articles