英文:
Change Seleniums default TimeoutException
问题
在我的测试中,一些通过“css选择器”定位的元素需要很长时间才会出现,因为服务器非常慢。在通过Jenkins运行测试时,我经常会遇到这个错误,但在Eclipse上本地运行测试时却不会出现。
> org.openqa.selenium.TimeoutException: 期望的条件失败:
> 等待元素可见,定位方式为By.cssSelector:
> #ctl00_ContentPlaceHolder1_uctlSettingUpPaymentCollectionGrid1_gvGroup_ctl02_deleteGroup
> (尝试了10秒,间隔500毫秒)
是否可以在Selenium中将这个超时时间增加到10秒以上?
英文:
In my test some of the elements which are located via a css selector
take a long time to appear as the servers are very slow. I often get this error when running the tests through jenkins but not locally on eclipse.
> org.openqa.selenium.TimeoutException: Expected condition failed:
> waiting for visibility of element located by By.cssSelector:
> #ctl00_ContentPlaceHolder1_uctlSettingUpPaymentCollectionGrid1_gvGroup_ctl02_deleteGroup
> (tried for 10 second(s) with 500 milliseconds interval)
Is it possible to increase this to more then 10 seconds on selenium?
答案1
得分: 1
尝试使用隐式等待 - 文档在此
有一种与显式等待不同的等待方式,称为隐式等待。通过隐式等待,WebDriver 在尝试查找任何元素时,会在一定的持续时间内轮询DOM。当网页上的某些元素不立即可用并需要一些时间加载时,这可能会很有用。
您只需为您的驱动程序设置一次,它会动态等待,直到达到您指定的超时时间。
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
或者,您可以针对需要的每个元素使用显式等待:
new WebDriverWait(driver, Duration.ofSeconds(30)).until(ExpectedConditions.elementToBeClickable(<<Your-Identifier>>));
通过显式等待,您可以确保某些预期条件已准备就绪,并且您可以控制元素的超时时间以与之同步。
Java中的预期条件列表在此处。
通常建议您尽可能选择一种方法:
警告:不要混合使用隐式和显式等待。这样做可能会导致不可预测的等待时间。例如,将隐式等待设置为10秒并设置显式等待为15秒可能会在20秒后导致超时。
英文:
Try implicit waits - docs here
> There is a second type of wait that is distinct from explicit wait
> called implicit wait. By implicitly waiting, WebDriver polls the DOM
> for a certain duration when trying to find any element. This can be
> useful when certain elements on the webpage are not available
> immediately and need some time to load.
You set it once for your driver and it's a dynamic wait up until your specified timeout.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Alternatively, you can use explicit waits per element that needs it:
new WebDriverWait(driver, Duration.ofSeconds(30)).until(ExpectedConditions.elementToBeClickable(<<Your-Identifier>>));
With explicit waits you can ensure certain ExpectedConditions are ready and you control the timeout for the element to synchronise with.
A list of expected conditions for Java are here
It is generally recommended you choose on approach if possible:
> Warning: Do not mix implicit and explicit waits. Doing so can cause
> unpredictable wait times. For example, setting an implicit wait of 10
> seconds and an explicit wait of 15 seconds could cause a timeout to
> occur after 20 seconds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论