如何在Java Selenium Driver中单击画布的中心?

问题描述 投票:0回答:1

我正在尝试编写代码以单击网页中的画布中心。

这是下面的代码:

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()方法移动鼠标,则可以执行click动作(因为您可以看到'clicked:1'),但是它没有单击canvas元素的中心。如果我试图在画布元素上移动鼠标,则会引发异常。

如何使它起作用并单击画布元素的中心?

java selenium canvas click
1个回答
0
投票

相关的DOM Tree本来可以帮助我们构造一个规范的答案。但是,在处理<canvas>元素时,您需要考虑一些事项:

  • [<canvas>的左上角具有坐标(00),而
  • 使用W3C Action类命令,偏移量位于元素中心。

通常,<canvas>元素将具有以下属性:

  • width
  • height
  • [style包含属性widthheight

例如:

<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;

作为:

[类命令的当前实现,偏移量是从元素中心开始。

因此,您可以使用以下解决方案:

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();


参考

您可以在以下位置找到相关的详细讨论:

© www.soinside.com 2019 - 2024. All rights reserved.