我正在尝试编写代码来单击网页中的 Canvas 中心。
下面是代码:
private static void clickCanvasCenter() {
WebElement we = driver.findElement(By.tagName("canvas"));
int x = we.getSize().width/2;
int y = we.getSize().height/2;
Actions builder = new Actions(driver).moveToElement(new WebDriverWait(driver,20)
.until(ExpectedConditions.elementToBeClickable(we)));
System.out.println("width:" + x + "\theight:" + y);
builder.click().build().perform();
System.out.println("clicked:1");
builder.moveByOffset(x, y).click().build().perform();
System.out.println("clicked:2");
}
输出是:
width:683 height:341
clicked:1
Exception in thread "main" org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: move target out of bounds
(Session info: chrome=79.0.3945.130)
在上面的代码中,如果我没有通过 moveByOffset() 方法移动鼠标,则可以执行单击操作(因为您可以看到“clicked:1”),但是它没有单击 Canvas 元素的中心。如果我尝试将鼠标移过 Canvas 元素,则会引发异常。
如何使其工作并单击 Canvas 元素的中心?
最佳答案
相关DOM Tree会帮助我们构建一个规范的答案。然而,在处理<canvas>
时您需要考虑以下几点:
- 左上角
<canvas>
具有坐标(0
,0
),而 - 使用 W3C Action 类命令,偏移量是从元素中心开始的。
通常,<canvas>
元素将具有以下属性:
-
width
-
height
-
style
包含属性width
,height
等等
举个例子:
<canvas id="canvas" width="227" height="294" style="position: absolute; display: block; background-color: rgb(255, 255, 255); width: 227.53px; height: 294px;"></canvas>
现在,单击 <canvas>
的中心网页中的元素,您真的不需要计算:
-
we.getSize().width/2;
-
we.getSize().height/2;
如:
The current implementation of Action class commands, offsets are from the center of element.
因此,您可以使用以下解决方案:
WebElement canvas = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.id("canvas")));
//clicking on the centre
new Actions(driver).moveToElement(canvas).click().build().perform();
如果您想单击偏移量,则需要使用 moveByOffset()
如下:
new Actions(driver).moveToElement(canvas, 0, 0).moveByOffset((683/5)*3,(341/5)*3).click().build().perform();
<小时/>
引用
您可以在以下位置找到相关的详细讨论:
关于java - 如何在 Java Selenium 驱动程序中单击 Canvas 的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061414/