有时Webdriver无法找到webelement并抛出nosuchelementexception但很多时候相同的测试运行完美

时间:2014-06-24 17:09:54

标签: java html selenium xpath selenium-webdriver

我创建了一个测试脚本,我想在其中单击编辑按钮然后关闭窗口。大多数情况下代码按预期工作,但是相同代码的一些时间我得到了nosuchelement异常。我经历了论坛中提出的类似问题,但没有一个解决方案适合我。下面我将java代码与HTML代码一起放在希望找到解决方案。

for(String newwindow : window.getWindowHandles()){
    //swithching to the new pop up using window.switchTo().window(passing newwindow as argument)    
    window.switchTo().window(newwindow);}
    //getting title of new window using getTitle() method
    System.out.println("NewWindow Title"+ window.getTitle());
    window.findElement(By.xpath(".//*[@id='edit_resume_section3_open' and not(@disabled)]")).click();
    window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
    System.out.println(window.findElement(By.xpath("//input[@name='title']")).getAttribute("value"));
    window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
    window.findElement(By.id("update")).click();
    window.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
    window.close();

Html Code for the webelement-
<head>
<body class="bg_lightgreen" marginwidth="0" marginheight="0" onload="" leftmargin="0"    topmargin="0" style="">
<iframe id="_yuiResizeMonitor" style="position: absolute; visibility: visible; width: 10em; height: 10em; top: -120px; left: -120px; border-width: 0px;"/>
<div id="fade_nation_mismatch" class="black_overlay"/>
<div id="fade_visual_resume" class="black_overlay"/>
<div id="show_visual_resume" class="white_content" style="position: absolute; top: 25%;">
<table class="bg_purple" width="100%" cellspacing="0" cellpadding="0" border="0">
<table class="bg_white" width="998" cellspacing="0" cellpadding="20" border="0" align="center">
<table class="bg_white" width="998" cellspacing="0" cellpadding="20" border="0" align="center">
<tbody>
<tr>
<td class="font_15 txt_purple bold" width="203" style="padding-bottom:5px; width:250px; word-wrap: break-word;">1.6YR Experiance/BSC(CS)</td>
<td width="715" style="padding-bottom:5px;">
<a id="edit_resume_section3_open" class="thickbox" title="Professional Details"  style="cursor:pointer" onclick="showEditSection(3);">[Edit]</a>
</td>
</tr>

下面的代码是给出问题的按钮     [编辑]

2 个答案:

答案 0 :(得分:1)

尝试使用

WebElement yourElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("yourElementId")));

要确保您的元素已加载,那么您可以使用您的元素。或另一个ExpectedConditions

答案 1 :(得分:0)

有时加载可能需要更长时间,因此您可以等到元素加载到最大时间,而不是使用implicitlyWait:

private void waitUntilIsLoaded(WebDriver driver, By selector, int maxTime){
   wait.wait(driver, selector, maxTime);
}

当测试无法检查元素是否显示时,您还可以修改代码以截取屏幕截图,因为它可能由于某些错误而无法加载。