The best VPN 2024

The Best VPS 2024

The Best C# Book

How to use C# judge selenium element can be clicked, selected, and visible

how to use C# judge selenium element can be clicked, selected, and visible? I recently used selenium to write an automated testing tool. Of course, I use the C# language. I often check whether the element can be clicked, whether it can be selected, and whether the element In a visible state, etc.

How to use C# judge selenium element can be clicked, selected, and visible
How to use C# judge selenium element can be clicked, selected, and visible

C# judge selenium element can be clicked

When you use C# to determine whether an element can be clicked, you need to call the FindElement method or FindElements to find it. After finding it, you will find that this element is derived from the IWebElement interface, so it can be detected through the properties provided by IWebElement.

    public interface IWebElement : ISearchContext
    {
        bool Displayed { get; }
        Point Location { get; }
        bool Selected { get; }
        bool Enabled { get; }
        string Text { get; }
        string TagName { get; }
        Size Size { get; }

        void Clear();
        void Click();
        string GetAttribute(string attributeName);
        string GetCssValue(string propertyName);
        string GetDomAttribute(string attributeName);
        string GetDomProperty(string propertyName);
        [Obsolete("Use the GetDomProperty method instead.")]
        string GetProperty(string propertyName);
        ISearchContext GetShadowRoot();
        void SendKeys(string text);
        void Submit();
    }

How to use C# judge selenium element can be clicked, selected, and visible

As in the above code snippet, you can check through the Enabled and Displayed properties, but usually, I choose to use the method of catching exceptions to click safely. When an error occurs, I will display it on the interface through the callback function to indicate what error has occurred.

How to use C# judge selenium element can be clicked, selected, and visible
How to use C# judge selenium element can be clicked, selected, and visible

The following code is what I did in the project. Because I encapsulated it into an extension method.

/// <summary>
/// Click safely, if an error occurs, record the log
/// </summary>
/// <param name="element"></param>
/// <param name="outPut">ouput or save error log</param>
public static bool ClickSafe(this IWebElement element, Action<string> outPut = null)
{
    if (element == null) return false;
    try
    {
        outPut?.Invoke($"Start to click [{element.Text}] function or link!");
        element.Click();
        //System.Threading.Thread.Sleep(200);
        return true;
    }
    catch (Exception ex)
    {
        outPut.Invoke("\r\n***************************************** ************************************************** ***\r\n");
        outPut?.Invoke($"Click [{element.Text}] error, reason: \r\n{ex.Message}\r\n\r\nstack information:\r\n{ex.StackTrace}");
        outPut.Invoke("\r\n***************************************** ************************************************** ***\r\n");
        return false;
    }
}

How to use C# judge selenium element can be clicked, selected, and visible

This tool I wrote is used for automated testing of asp.net webform development website projects, you know, asp.net webform uses server controls, so some controls can be postback, I also wrote an extension for select Method, you can simulate the client to trigger the change event of select tag. It should be noted here that the client depends on jquery.

Selenium randomly sets the selected value of the select tag

/// <summary>
/// The drop-down box randomly selects a value
/// </summary>
/// <param name="element"></param>
/// <param name="driver"></param>
/// <param name="outPut"></param>
/// <returns></returns>
public static (string name, string value) RandomSelected(this IWebElement element, IWebDriver driver, Action<string> outPut = null)
{
    if (driver == null || element == null) return (string.Empty, string.Empty);
    var options = element.FindElements(By.TagName("option")).Where(x => !x.GetAttribute("value").IsNullOrEmpty()).ToList();
    if (options.Count> 0)
    {
        var ran = GetRandomElement(options);
        var ranValue = ran.GetAttribute("value");
        var id = element.GetAttribute("id");
        var name = element.GetAttribute("name");

        SelectElement oSelect = new SelectElement(element);
        oSelect.SelectByValue(ranValue);
        outPut?.Invoke($"drop-down box name[{name}]|drop-down box id[{id}]|randomly selected value [{ranValue}]|randomly selected text value[{ran.Text}]");
        return (name, ranValue);
    }
    return (string.Empty, string.Empty);
}

/// <summary>
/// Randomly select the value of the drop-down box and trigger its change event (postback on the asp.net page)
/// </summary>
/// <param name="element"></param>
/// <param name="driver"></param>
/// <param name="outPut"></param>
public static (string name, string value) RandomSelectedAndChange(this IWebElement element, IWebDriver driver, Action<string> outPut = null)
{
    if (driver == null || element == null) return (string.Empty, string.Empty);
    var options = element.FindElements(By.TagName("option")).Where(x => !x.GetAttribute("value").IsNullOrEmpty()).ToList();
    if (options.Count> 0)
    {
        var ran = GetRandomElement(options);
        var ranValue = ran.GetAttribute("value");
        var id = element.GetAttribute("id");
        var name = element.GetAttribute("name");

        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        string script = $"$(\"#{id}\").selectpicker(\"val\",\"{ranValue}\"); $(\"#{id}\").trigger('change ');";
        outPut?.Invoke($"Postback function: drop-down box name [{name}] | drop-down box id [{id}] | random selection of value [{ranValue}] | random selection of text value [{ran.Text}] ");
        js.ExecuteScript(script);
        return (name, ranValue);
    }
    return (string.Empty, string.Empty);
}

How to use C# judge selenium element can be clicked, selected, and visible

I wrote a method for the random selection value of the ordinary select tag and the method for selecting the value randomly for the select tag with a postback function. Both methods have 2 return values. Next, you will see the code for how to use it.

Call in code

var selects = driver.FindElements(By.XPath("//div[@id='odiv']//child::select")).ToList();
int total = selects.Where(x => x.IsPostBack()).Count(); //How many drop-down boxes on the page have postback query function

foreach (var item in selects)
{
    if (item.IsPostBack()) continue;
    var val = item.RandomSelected(driver, ShowLog);
    sb.AppendFormat(" {0} :{1} |", val.name, val.value);
}
bool success = false;
if (driver.HasQueryButton(out IWebElement query))
{
    success = query.ClickSafe(ShowLog);
    SaveErrorLog(driver, sb.ToString().TrimEnd('|'));
}
if (success) //Execute postback query
{
    sb.Clear();
    while (total != 0)
    {
        selects = driver.FindElements(By.XPath("//div[@id='queryAreaControlID']//child::select")).Where(x => x.IsPostBack()).ToList();
        var item = selects[total-1];
        var val = item.RandomSelectedAndChange(driver, ShowLog);
        sb.AppendFormat(" {0}:{1} |", val.name, val.value);
        Thread.Sleep(500);
        SaveErrorLog(driver, sb.ToString().TrimEnd('|'));
        total--;
    }
}

How to use C# judge selenium element can be clicked, selected, and visible

In the current context code snippet, the driver variable that appears is an instance of the IWebDriver type, which means you can use ChromeDriver or FireFoxDriver, etc.

 How to use C# judge selenium element can be clicked, selected, and visible
How to use C# judge selenium element can be clicked, selected, and visible

Summary

When you use C# judge selenium element can be clicked, selected, and visible, need note these tips:

  • Before judging whether the element can be clicked, you need to call FindElement or FindElements find it
  • Some elements are not displayed on the page, you need to check whether the Displayed property is True
  • Sometimes you also need to check the Enabled state, because its state may be changed by js.

Leave a Comment