Navigating through the properties of an IWebElement object

In my current project, I am using C# and Selenium with the page object model approach to automate testing on a website.

I have implemented a page object that includes a list of IWebElement properties representing various buttons and links on the website that need to be interacted with.

This is what the page object looks like :

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace UITesting
{
    class PlansPage
    {
        private IWebDriver _driver;

        public PlansPage(IWebDriver driver)
        {
            _driver = driver;
        }

        // Buttons & Links
        public IWebElement homeButton => _driver.FindElement(By.ClassName("navbar-brand"));
        public IWebElement licenseLink => _driver.FindElement(By.XPath("//a[@href='/#/account'][@class='ng-binding']"));
        public IWebElement plansLink => _driver.FindElement(By.XPath("//a[@href='#/plans']"));
    }
}

While I am able to access each IWebElement directly during testing :

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;

namespace UITesting
{
    class PlansTest
    {
        // Setting up driver & plans page
        IWebDriver driver = new FirefoxDriver();
        PlansPage plansPage = new PlansPage(driver);

        // Clicking on individual elements
        plansPage.homeButton.Click();
        plansPage.licenseLink.Click();
        plansPage.plansLink.Click();
    }
}

My goal now is to programmatically click on every button present on the page. To achieve this, I want to iterate through the IWebElements in plansTest and call the Click() method on each element as shown below :

foreach (IWebElement element in plansPage)
{
    element.Click();
}

To view these elements as properties and print out their names, I can do so by iterating through them like this:

foreach (var property in plansPage.GetType().GetProperties()) 
{
    Console.WriteLine(property.Name);
}

However, attempting to execute property.Click() results in an error message indicating that PropertyInfo does not contain a definition for `Click`.

Upon further investigation, I attempted to retrieve the value of the property and then assign it to an IWebElement, but encountered a conversion error :

Cannot implicitly convert type 'object' to 'OpenQA.Selenium.IWebElement'. An explicit conversion exists (are you missing a cast?)

My aim is to find a way to iterate through the properties of an object in order to obtain an IWebElement object. How can I achieve this?

Answer №1

Why do you feel the need to click on every button on the page? There may be a more efficient way to accomplish your task.

In response to your question, it seems like you are forgetting to include an explicit cast. One approach is to use the standard cast, which will throw an exception if the cast is not possible:

var temp = property.GetValue(plansPage, null);
IWebElement element = (IWebElement) temp;
Console.WriteLine(element);

Another option is to use a safe cast, where the null value (if the type is nullable) is returned in case of failure:

var temp = property.GetValue(plansPage, null);
IWebElement element = temp as IWebDriver;
Console.WriteLine(element);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Processing JSON Serialization from Controller to AJAX Response

I'm struggling to find the correct way to use an HttpWebRequest, and then convert its response into a readable format of JSON for a JavaScript AJAX function. If I just return the raw text, it includes escaping slashes in the response. If I deserializ ...

Tips for reducing the browser window size in Selenium WebDriver 3

Once the browser window has been maximized using driver.manage().window().maximize();, what is the method to minimize it in Selenium WebDriver with Java? ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Show on Screen as Label Text

I am looking to change the display format from a popup box to a label text. How can I achieve this using JQuery? JQuery <script type="text/javascript> function ShowCurrentTime() { PageMethods.GetCurrentTime(document.getElementById("<%=txtUserNam ...

use selenium to choose an element

I'm attempting to target a specific element in the HTML code below: <ul class="selectReplace opened"> <li class="default">Standard pizzas</li> <li class="first">Standard pizzas</li> <li class="">Special pizzas</ ...

The Pylance tool reported that the import statement for "selenium" could not be resolved in the code

While editing a file in VS code, I encountered an error message stating: Import "selenium" could not be resolved Pylance (reportMissingImports). Below is the code snippet from metachar: # Coded and based by METACHAR/Edited and modified for Micro ...

Revamp Your Service Naming and Nickname with Swagger Codegen IO

Is it possible to customize the Swagger IO CodeGen naming conventions for generating Angular API Service Proxies? Check out Swagger Editor here The current convention combines API, Controller Name, Controller Method, and HTTP Action. public apiProductGet ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Storing the URL of the current page in Chrome to a variable using Python

When using Selenium, I encountered a challenge on a specific page that was masking the real URL when I tried to use "driver.current_url". Instead of the actual link, it provided a generic URL. Feel free to test it yourself at: . Follow the Google Drive lin ...

Is storing HTML tags in a database considered beneficial or disadvantageous?

At times, I find myself needing to modify specific data or a portion of it that originates from the database. For instance: If there is a description (stored in the DB) like the following: HTML 4 has undergone adjustments, expansions, and enhancements b ...

AssessmentMonitor using Selenium

I have implemented TestWatcher to perform certain actions based on test output. However, the function that I need to call, createScreenShot in testFailed, requires a driver as an input parameter. Unfortunately, the driver is protected and not static, as al ...

What is the best method to empty an input field using Intern JS?

I have developed a code snippet for inline editing table fields. This functionality allows users to click on an element, which then gets replaced by an input field for editing. Once the modification is made, the input field is removed and replaced with a s ...

Proceed with the process as long as the Element remains hidden

Currently, I am conducting UI testing using C#/Selenium on a data entry section that is followed by a results window. The results can either be present or absent, and I am examining both scenarios. To facilitate this testing, I have created a method outli ...

(Pathlib) Error when concatenating Root and 'foldername' - TypeError: unsupported operand types for +: 'WindowsPath' and 'str'

I have encountered an issue with my code. I have organized it in a folder structure where the main code is located at the root level, and I have created a separate folder named "Backups" within this root folder. The problem arises when I try to concatenate ...

In order to select a checkbox within an alert popup using Selenium C# without an xpath, you may encounter the issue of disabled right-click for inspection

Is there a way to select a checkbox within an alert popup using Selenium C# when the checkbox does not have a specified xpath? It seems that inspection is disabled, preventing right-clicking. https://i.stack.imgur.com/HoCiK.png ...

Strategies for dealing with a non-existent popup window in Selenium WebDriver using Java

My current challenge involves a popup window that is not recognized by WebDriver. https://i.stack.imgur.com/BRUsB.png Since there is no WindowHandle for this popup, I am unable to interact with it like an Alert. https://i.stack.imgur.com/ldoVI.png Howeve ...

Utilizing a Batch script to manage temporary folders in automation tests with Selenium

Frequent running of selenium tests leads to the accumulation of numerous 'anonymous-web-driver' profiles in the temp folder for Firefox and 'scoped-dirs' for Chrome. To address this issue, I devised the following batch script: @echo o ...

Interacting with an iframe element using Selenium in Python

I have a webpage with an iframe embedded, and I'm using Selenium for test automation: <iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="dis ...

I'm just starting out with Python and I'm wondering how I can access the initial values for precipitation, temperature, wind gust, and humidity

from selenium import webdriver import time PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get("https://www.metoffice.gov.uk/weather/forecast/gcvwr3zrw#?date=2020-07-12") time.sleep(5 ...

Utilizing a JSON object to send data to a C# WebAPI POST endpoint that accepts a parameter of a generic abstract class

I have a generic abstract class that defines the structure of an object to be POSTed to this endpoint. The class is as follows, with an example implementation: public abstract class Animal<T> { public string Name { get; set; } pu ...