java - 如何在 Java Selenium 驱动程序中单击 Canvas 的中心?

标签 java selenium canvas click

我正在尝试编写代码来单击网页中的 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>具有坐标( 00 ),而
  • 使用 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/

相关文章:

xpath - Selenium WebDriver 查找第 n 个元素

python - 如何使用 Python 使用 Selenium Webdriver 获取此 html 中的某些文本值?

canvas - 将 SVG ARCTO 映射到 HTML Canvas ARCTO

java - 流是否会在出错时自动关闭?

java - 每次当我滚动随机项目时更改项目背景颜色时,项目也会更改背景颜色

java - 是否可以在tomcat7中将 'http://localhost:8080/myapplication'更改为类似 'http://myApp/'的内容?

java - 如何使用 JNA 将 com.sun.jna.Structure 从 Java 传递到 C 中的结构

javascript - Selenium 构建 Internet Explorer 驱动程序 javascript 错误

javascript - 为什么在旋转之前必须先平移才能在 Canvas 中围绕自身旋转元素?

javascript - 无法通过 HTML 在屏幕上显示 Canvas