2014-06-20 72 views
4

我在Windows 8.1上使用PhantomJS 1.9.7,我将在输入用户名和密码后点击登录按钮。我可以写用户名和密码,但是当我想让PhantomJS点击按钮时,它可以找到该元素,但无法点击该元素。 我在之前的文章中发现我需要创建事件并使用“dispatchEvent”。我这样做,但我如下得到了一个错误:PhantomJS无法点击现有元素

TypeError: 'undefined' is not a function (evaluating 'elm.dispatchEvent(event)')

我也试图从事件监听得到帮助,但我得到了同样的错误了点。

我怎样才能点击一个元素?

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 = "*******"; 
     return document.getElementsByTagName("Button"); 
    }); 
    return 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); 
} 
+0

你会写你使用点击按钮的代码? –

+0

@cracker:请不要使用[内嵌代码跨度突出显示单词](http://meta.stackexchange.com/questions/135112/inline-code-spans-should-not-be-used-for-emphasis-正确) - 往往没有必要,如果真的需要强调,请[使用粗体或斜体](http://www.etf.europa.eu/authorssite.nsf/Pages/Use%20of%20bold%20and%20italics )代替。内联代码跨度仅用于语句中的代码(顾名思义):编辑帖子时请记住这一点。 –

+0

当然,谢谢我下次会照顾 – cracker

回答

-1

jQuery中只需插入并做

$(selector).trigger('click'); 

请注意,如果该页面使用异步后,页面加载事件不会触发,但它“加载”,你必须等待为回应。

可能会设置等待几秒钟,这将足以让异步帖子回来。

+0

只是建议“用jQuery来代替!”没有解决OP所具有的特定问题。 –

+0

亲爱的@sphanley:只需注意:海报说:dispatchEvent是未定义的。 Jquery有这个方法。当然。 – Sesertin

+0

是的,但这就像告诉某人要求帮助让他们的车开始换乘公共汽车。当然,jQuery可以触发一个元素的点击,但OP使用的是PhantomJS,而不是jQuery。 –

0

代码有两个问题。第一个DOM元素不能从页面上下文(page.evaluate)之外传递。从docs相应行:

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

所以submitButton[null]。由于返回数组,错误消息不会显示实际问题。由于DOM元素无法传递到外部,因此点击必须发生在page.evaluate之内。

由于page.evaluate是沙盒,所以click函数必须在页面上下文中定义。来自外部的变量和函数不能直接访问。

一个可能的脚本是这样的:

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

page.open('URL', function() { 
    enterUserAndPassAndLogin(); 
    setTimeout(function(){ 
     // wait a little to maybe see the 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]); 
    }); 
}