此问题与询问的here相似。但是,在那种情况下,海报的最终目的似乎实际上是选择一段文本,他们能够找到一种不涉及单击的变通方法。
像上述问题中的用户一样,我最初认为可以通过调用click方法三次来模拟三次单击。
new Actions(driver)
.moveToElement(svgElement, posX, posY)
.click()
.click()
.click()
.perform()
但是,这不起作用,因为我的JavaScript代码检查
detail
实例的UIEvent
属性,并且每次对1
的调用始终为click
。因此,以下代码段:function clickHandler (event) {
if (event.detail == 1) {
singleClickHandler()
}
if (event.detail == 2) {
doubleClickHandler()
}
if (event.detail == 3) {
tripleClickHandler()
}
通过Selenium调用时,导致
singleClickHandler
被调用3次,而通过浏览器(Firefox)手动执行时,singleClickHandler
,doubleClickHandler
和tripleClickHandler
分别被调用一次。如何通过硒触发
detail
等于3的点击事件? 最佳答案
当前的api没有提供一种模拟三次点击的方法,该方法会发出带有点击计数的一次点击事件。
因此,您最好的机会是使用executeScript模拟事件:
String JS_CLICK_TRIPLE =
"var target = arguments[0]; " +
"var offsetX = arguments[1]; " +
"var offsetY = arguments[2]; " +
"var rect = target.getBoundingClientRect(); " +
"var cx = rect.left + (offsetX || (rect.width / 2)); " +
"var cy = rect.top + (offsetY || (rect.height / 2)); " +
" " +
"emit('mousedown', {clientX: cx, clientY: cy, buttons: 1}); " +
"emit('mouseup', {clientX: cx, clientY: cy}); " +
"emit('mousedown', {clientX: cx, clientY: cy, buttons: 1}); " +
"emit('mouseup', {clientX: cx, clientY: cy}); " +
"emit('mousedown', {clientX: cx, clientY: cy, buttons: 1}); " +
"emit('mouseup', {clientX: cx, clientY: cy}); " +
"emit('click', {clientX: cx, clientY: cy, detail: 3}); " +
" " +
"function emit(name, init) { " +
"target.dispatchEvent(new MouseEvent(name, init)); " +
"} " ;
Actions action1 = new Actions(driver);
action1.moveToElement(yourElement, posX, posY).perform();
((JavascriptExecutor)driver).executeScript(
JS_CLICK_TRIPLE, yourElement, posX, posY);