ALIENQuake
ALIENQuake

Reputation: 282

Test if element is present

I've added Selenium WebDriver to the Powershell and create WebDriver instance:

Add-Type -path C:\Windows\net40\WebDriver.dll
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
$driver.Url = "https://www.google.com"

Now I want to find input field:

$singleRecord = ($driver.FindElementByCssSelector("input.gbqfif"))

I found several examples how to "Test if element is present" in C#:

Selenium WebDriver - Test if element is present

Selenium c# Webdriver: Wait Until Element is Present

There is also guide here:

IWebDriver driver = new FirefoxDriver();
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.Id("someDynamicElement"));
    });

but I cannot create something similar in Powershell, and almost all my tests fails because it takes time for page to load elements.

Upvotes: 0

Views: 1172

Answers (2)

Andreas Karz
Andreas Karz

Reputation: 410

The only really safe way is:

    static bool isElementPresent(dynamic element, By by)
    {
        try
        {
            element.FindElement(by);
            return true;
        }
        catch (NoSuchElementException e)
        {
            return false;
        }
    }

This method accept both, an IWebDriver or an IWebElement, as a starting point for FindElement().

And so you can us it on a LINQ Query:

_infodeskSectionContracts = from contract in _infodeskSection.FindElements(By.CssSelector(_base + " * ul.list.type-itemlist li")) select new Contract { element = contract.FindElement(By.TagName("a")), label = contract.FindElement(By.TagName("h4")).Text, contractNumber = (isElementPresent(contract, By.TagName("p")) ? contract.FindElement(By.TagName("p")).Text : "0000") };

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201932

I'm not familiar with this API but if you're having problems getting it to work in PowerShell but it works in C#, then just create C# wrappers around the functionality you need that you can access from PowerShell. You can do this fairly easily with the Add-Type command. From the first example in its doc page:

$source = @"
public class BasicTest { 
    public static int Add(int a, int b) {
        return (a + b);
    }  
    public int Multiply(int a, int b) {
        return (a * b);
    }
}
"@
Add-Type -TypeDefinition $source

[BasicTest]::Add(4, 3)
$basicTestObject = New-Object BasicTest
$basicTestObject.Multiply(5, 2)

As you find C# code for this API that does work, you can plop it into a C# wrapper class that you can call from PowerShell. The key is to avoid features PowerShell can't handle like C# static extension methods.

Upvotes: 1

Related Questions