简体   繁体   中英

Selenium c#: Wait Until Element is Present Without Waiting the Time Given, Else Time Out

To explain further, I am currently working with selenium and c#. My problem is, my tool runs very fast without waiting the element to be ready.

Thread.Sleep() is not advisable for instance.

The given time to wait is 2 secs. the element will be present in 1 or more secs. after the Thread.Sleep() so the code line is not reliable.

Or the element is present but still waiting to finish Thread.Sleep() so it is time consuming.

What I want is, if the element is found then no need to wait on the given time, and if not found at the given time then time out.

This is exactly what explicit wait and expected conditions are for.

Uses example

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By locator));

This will wait up to 5 seconds for the element to be visible. If successful the element will be returned, if not it will throw TimeoutException .

Update

ExpectedConditions has moved and is now located in SeleniumExtras.WaitHelpers

'ExpectedConditions' is obsolete: 'The ExpectedConditions implementation in the .NET bindings is deprecated and will be removed in a future release. This portion of the code has been migrated to the DotNetSeleniumExtras repository on GitHub ( https://github.com/DotNetSeleniumTools/DotNetSeleniumExtras )'

To avoid many changes in the existing code import the ExpectedConditions to a variable called ExpectedConditions . The rest of the code remains the same

using ExpectedConditions = SeleniumExtras.WaitHelpers.ExpectedConditions;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM