Skip to content

Instantly share code, notes, and snippets.

@BashkaMen
Created August 26, 2021 19:16
Show Gist options
  • Save BashkaMen/697bad7aae8785a9fde6ce6eee8093e3 to your computer and use it in GitHub Desktop.
Save BashkaMen/697bad7aae8785a9fde6ce6eee8093e3 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace SeleniumExt
{
public static class DriverExt
{
public static async Task<IWebElement> WaitFindElement(this IWebDriver driver, By by, Func<IWebElement, bool> predicate)
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while (!cts.IsCancellationRequested)
{
var elements = driver.FindElements(by).Where(predicate).ToArray();
if (elements.Any()) return elements.First();
await Task.Delay(1000);
}
var screen = (ITakesScreenshot) driver;
var screenshot = screen.GetScreenshot();
var id = Guid.NewGuid();
await File.WriteAllBytesAsync($"Data/screenshots/{id:N}.jpg", screenshot.AsByteArray, CancellationToken.None);
throw new Exception($"[{id}] Element not found by {by}");
}
public static Task<IWebElement> FindRaw(this IWebDriver driver, By by)
=> driver.WaitFindElement(by, s => true);
public static Task<IWebElement> FindActive(this IWebDriver driver, By by)
=> driver.WaitFindElement(by, s => s.Displayed && s.Enabled);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment