javascript - PhantomJS cannot click on existing elements -
javascript - PhantomJS cannot click on existing elements -
i utilize phantomjs 1.9.7 on windows 8.1 , going click on login button after typing username , password. can write username , password but, when want phantomjs click on button, can find element not able of clicking on that. found in previous posts need create event , utilize "dispatchevent". did got error follows:
typeerror: 'undefined' not function (evaluating 'elm.dispatchevent(event)')
i tried help eventlistener got same error that.
how can click on element?
var page = require('webpage').create(); page.open('url', function() { var submitbutton = enteruserandpassandlogin(); click(submitbutton); phantom.exit(); }); function enteruserandpassandlogin() { var element = page.evaluate(function() { document.queryselector('input[name="username"]').value = "*******"; document.queryselector('input[name="password"]').value = "*******"; homecoming document.getelementsbytagname("button"); }); homecoming element; } function click(elm) { var event = document.createevent("mouseevent"); event.initmouseevent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elm.dispatchevent(event); }
there 2 problems code. first dom elements cannot passed page context (page.evaluate
) outside. corresponding line docs:
note: arguments , homecoming value evaluate function must simple primitive object. rule of thumb: if can serialized via json, fine.
closures, functions, dom nodes, etc. not work!
so submitbutton
[null]
. because array returned, error message doesn't show actual problem. since dom element cannot passed outside, click must happen within of page.evaluate
.
since page.evaluate
sandboxed click
function must defined within of page context. variables , functions outside cannot straight accessed.
a possible script this:
var page = require('webpage').create(); page.open('url', function() { enteruserandpassandlogin(); settimeout(function(){ // wait little maybe see click result phantom.exit(); }, 1000); }); function enteruserandpassandlogin() { page.evaluate(function() { function click(elm) { var event = document.createevent("mouseevent"); event.initmouseevent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elm.dispatchevent(event); } document.queryselector('input[name="username"]').value = "*******"; document.queryselector('input[name="password"]').value = "*******"; click(document.getelementsbytagname("button")[0]); }); }
javascript jquery click phantomjs dispatchevent
Comments
Post a Comment