首页 文章

使用selenium webdriver找到由javascript创建的元素

提问于
浏览
1

我'm new in Selenium and Java, i'使用selenium(java)在自动化测试项目中工作,今天我有 driver.findElement 的问题,我想找的元素是由javascript创建的,我确定使用WebDriverWait等待目标元素呈现,甚至我使用thread.sleep并等待大约几分钟,但webdriver仍然无法找到该元素 .

这是我的问题,在html / js代码我有一个按钮,单击此按钮javascript将创建一个div,我需要使用selenium来定位它以使自动化测试工作 .

单击一个按钮后,javascript使div看起来像:

<div id="zm-view-frame" class="fade in"><div class="zm-view-header"><div class="zm-view-back"><a onclick="WFLandingpage.closePreview();" id="zm-view-close" class="button" href="javascript:void(0);"><span>Close</span></a></div><div id="zm-view-button"><a href="javascript:void(0);" onclick="WFLandingpage.showDesktop(this)" class="zm-display-desktop"><span>Desktop</span></a><a href="javascript:void(0);" onclick="WFLandingpage.showTablet(this)" class="zm-display-tablet"><span>Tablet</span></a><a href="javascript:void(0);" onclick="WFLandingpage.showMobile(this)" class="zm-display-phone"><span>Mobile</span></a><a href="javascript:void(0);" onclick="WFLandingpage.rotateView()" class="zm-display-rotate"><span>Rotate</span></a></div></div><iframe id="zm-display-iframe" src="page=mvc_landingpages&amp;act=templatepage&amp;preview=1&amp;templateId=landingpage3" style="padding-top: 63px; margin: 0px auto;" scrolling="yes" width="100%" height="609"></iframe></div>

那么,在我写的java代码中:

this.wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("zm-view-frame")));

然后 :

Tester.Browser.findElement(By.id("zm-view-frame")).click();

当然,我已定义 this.wait

public WebDriverWait wait = new WebDriverWait(Tester.Browser, 100);

我得到一个等待超时异常

我甚至使用了许多类型的 By ,如Xpath,css选择器,类......但仍然没有运气 .

我也使用Selenium IDE for firefox来获取元素,将它导出到java代码并在我的编辑器中查看然后执行相同的操作,但它对我来说不再适用 .

我真的坚持这个,你能给我一些帮助吗?

抱歉我的英语不好,非常感谢!

更新 - 这是我的html结构:html structure

UPDATE - I found the bug and have a solution

Reason :在上面的代码之前我有几行代码来检查iframe是否可用,代码如下:

this.wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(locator));

而且我不知道代码使驱动程序切换到那个iframe,所以我上面的代码找到元素是在错误的地方(上下文) .

Solution :所以我需要回到defaut上下文(回到父级),我的代码是这样的:

Tester.Browser.switchTo().defaultContent();

非常感谢@Naveen提醒我检查一下这个案子:) .

1 回答

  • 0

    I found the bug and have a solution

    原因:在上面的代码之前我有几行代码来检查iframe是否可用,代码如下:

    this.wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(locator));
    

    而且我不知道代码使驱动程序切换到那个iframe,所以我上面的代码找到元素是在错误的地方(上下文) .

    解决方案:所以我需要回到defaut上下文(回到父),我的代码是这样的:

    Tester.Browser.switchTo().defaultContent();
    

    非常感谢@Naveen提醒我检查一下这个案子:) .

相关问题