【问题标题】:Unable to locate the Element on Canvas using Selenium WebDriver无法使用 Selenium WebDriver 在画布上找到元素
【发布时间】:2018-03-28 15:29:09
【问题描述】:

我有一个使用 Vaadin 框架开发的应用程序,现在我需要单击 Canvas 上的矩形多边形。以下是 html 代码 这里我提供 Html 代码

<canvas width="1920" height="524" class="ol-unselectable" style="width: 100%; height: 100%;"></canvas>

我尝试使用使鼠标移到多边形上并单击的操作。

int x = (int) 5638326.333511386;
int y = (int)  2580101.9711508946;
driver.get("http://localhost:8080/internship");

WebElement ele = driver.findElement(By.xpath("//canvas[@class='ol-unselectable']"));
        //  driver.findElement(By.tagName("canvas"));
        //driver.findElemet(By.className("ol-unselectable"));
try {
    Actions builder = new Actions(driver);
    builder.moveToElement(ele, x, y);
    builder.clickAndHold();
    builder.release();
    builder.perform();
    } catch (Exception e) {
        // do nothing
    }

我收到以下错误

org.openqa.selenium.NoSuchElementException:无法定位元素: //canvas[@class='ol-unselectable'].

任何人都可以建议一些示例如何在画布上找到带有坐标的多边形并点击它。

【问题讨论】:

    标签: java canvas selenium-webdriver action polygon


    【解决方案1】:

    通常,canvas 元素嵌入在 iframe 中。 因此,首先,您必须找到 iframe 元素,然后在 iframe 中找到画布。例如:

    WebDriver driver = new FirefoxDriver(firefoxOptions);
            try {
                driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_empty");
                WebElement iframe = driver.findElement(By.name("iframeResult"));
                driver.switchTo().frame(iframe);
                WebElement canvas = driver.findElement(By.id("myCanvas"));
                System.out.println(canvas.getText());
            } finally {
                driver.quit();
            }
    

    我认为这段代码可能会对你有所帮助。

    编辑: 在与@RamanaMuttana 聊天以及他对已发布问题的更改后,我可以更好地了解他的需求。

    我们意识到仅使用 By.tagName 选择器就足以找到画布元素,如下面的代码所示:

    driver.findElements(By.tagName("canvas")).get(0);
    

    【讨论】:

    • 现在我可以去 iframe 之后,我无法找到 WebElement 画布 =driver.findElement(By.className(" .ol-unselectable"); 我收到错误“无法使用 css 选择器 == .ol-unselectable 找到元素”。你有什么想法吗,我需要使用 javascript 执行器来查找元素吗?
    • 在您的 HTML 代码中,类名前没有点 (.)。它只是 ol-unselectable。
    • 对不起,在我的测试代码中也没有“。”当我发表评论时,这只是我的错误
    • 另一种选择可能是在 stackoverflow.com/questions/7475449/… 中使用 By.cssselector。
    • 我尝试了以下但无法找到元素 WebElement element = driver.findElement(By.cssSelector("input[class='ol-unselectable']")); WebElement element = driver.findElement(By.cssSelector("canvas[class='ol-unselectable']")); WebElement element = driver.findElement(By.cssSelector("canvas.ol-unselectable")); WebElement element = driver.findElement(By.xpath("//canvas[@class='ol-unselectable']")); WebElement element = driver.findElement(By.xpath("//canvas[text() = 'ol-unselectable']"));
    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2014-05-29
    • 2016-08-31
    • 2023-04-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多