我的硒自动化脚本继续搜索元素,如果它没有在页面上找到。如何解决此问题

我正在自动化使用硒网络驱动程序与Java。编写我的脚本是为了检测“已创建重复记录”窗口消息,该消息仅在我们尝试添加“重复记录”时出现。


如果出现“重复记录窗口”,那么我的脚本绝对可以正常工作。但是,当“重复检测到的窗口”没有出现时,我的脚本会等待(继续搜索元素)很长时间,然后失败。(我的脚本等待的大约时间为10到15分钟)。


我想减少这个时间,并希望我的脚本“失败”,如果找不到元素。


请注意:我没有在我的代码中应用任何“显式”或“隐式”等待。


public boolean Contact_DuplicateDetection() throws InterruptedException { 

    return title_DuplicateRecordsDetected.isDisplayed();    


public void verify_Create_Contact_Duplicate_Detection_TestCase() { 

    Assert.assertTrue(Contact_DuplicateDetection()); 

}


慕妹3242003
浏览 99回答 4
4回答

墨色风雨

始终设置隐式等待。考虑到用户体验和性能,等待超过1分钟是没有意义的。        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);您还可以使用 try catch 来检查元素。    public boolean isElementWithXPathExist(String theXpath) {        try {            WebDriverWait wait = new WebDriverWait(driver,30);            wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath(theXpath))));        }catch(NoSuchElementException e) {            return false;        }catch(TimeoutException eT) {            return false;        }        return true;    }希望这会有所帮助

慕丝7291255

我的脚本等待的大约时间为 10 到 15 分钟似乎您以不适当的方式应用了隐式/显式等待。isDisplay()函数在 DOM 中存在的元素处于隐藏或可见状态时工作。如果元素不存在,则明显的错误是 。NoSuchElementException在这里,您可以使用解决方案;首先在页面对象中更改,然后按如下方式创建函数:WebElement title_DuplicateRecordsDetectedList<WebElement> title_DuplicateRecordsDetectedpublic&nbsp;boolean&nbsp;Contact_DuplicateDetection(){&nbsp; &nbsp;&nbsp;&nbsp;return&nbsp;title_DuplicateRecordsDetected.isEmpty()&nbsp;?&nbsp;false&nbsp;:&nbsp;true; }

繁星点点滴滴

非常感谢您的积极回复。我找到了解决方案。在这里public boolean verifyContactCreation() throws InterruptedException{&nbsp; &nbsp; driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);&nbsp; &nbsp; if(!driver.findElements(By.xpath("//button[@aria-label='Assign']")).isEmpty())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}使用查找元素而不是查找元素对我有用。同样重要的是,需要应用 0 秒的隐式等待。现在,我的脚本立即失败(如果找不到元素),而无需等待很长时间。

婷婷同学_

最好的方法是,如果您使用显式等待,因为有时由于网络负载过重,消息可能会稍后出现。显式等待还提供了超时功能,这将帮助您减少脚本的执行时间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java