如何在PhantomJS中单击元素?
page.evaluate(function() {
document.getElementById('idButtonSpan').click();
});
这会给我一个错误:"undefined is not a function...“
如果我转而
return document.getElementById('idButtonSpan');
然后把它打印出来
然后它打印对象对象,因此元素确实存在。
元素充当一个按钮,但它实际上只是一个span元素,而不是一个提交输入。
我可以点击这个按钮来使用Casper,但是Casper有其他限制,所以我回到了PhantomJS。
发布于 2013-04-11 20:06:11
.click()
不是标准的。您需要创建一个事件并将其分派:
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);
}
发布于 2013-07-22 22:18:10
作为@torazaburo响应的替代方案,您可以在PhantomJS中运行时将HTMLElement.prototype.click
存根。例如,我们使用PhantomJS + QUnit来运行我们的测试,在我们的qunit-config.js
中,我们有如下内容:
if (window._phantom) {
// Patch since PhantomJS does not implement click() on HTMLElement. In some
// cases we need to execute the native click on an element. However, jQuery's
// $.fn.click() does not dispatch to the native function on <a> elements, so we
// can't use it in our implementations: $el[0].click() to correctly dispatch.
if (!HTMLElement.prototype.click) {
HTMLElement.prototype.click = function() {
var ev = document.createEvent('MouseEvent');
ev.initMouseEvent(
'click',
/*bubble*/true, /*cancelable*/true,
window, null,
0, 0, 0, 0, /*coordinates*/
false, false, false, false, /*modifier keys*/
0/*button=left*/, null
);
this.dispatchEvent(ev);
};
}
}
发布于 2014-06-04 07:27:30
它并不美观,但我一直在使用它来允许我使用jQuery进行选择:
var rect = page.evaluate(function() {
return $('a.whatever')[0].getBoundingClientRect();
});
page.sendEvent('click', rect.left + rect.width / 2, rect.top + rect.height / 2);
但是,如果不使用document.querySelector(s)
,则始终可以用jQuery替换$(s)[0]
。
(它确实依赖于视图中的元素,即你的viewportSize.height足够大)。
https://stackoverflow.com/questions/15739263
复制相似问题