Convert Selenium Web Element to String C#



  • Basically, I'm making a programme that logs into the krispy kreme site and to test if login was successful, I am searching for a certain web element. I'm using selenium.

    For debugging purposes, and also as I may need to use this in future aspects of the program, I am trying to save the Element into a variable and then re-output with Console.WriteLine(), which works fine. When I try to use it in other scenarios e.g. If Statements. I get : cannot convert selenium element to string.

    How do I convert to a string? and store it in a new string variable.



  • If you need to save the Element into a variable, you can do the following:

    IWebElement submitbutton = driver.FindElement(By.Id("Submit"));
    

    Beware, if you navigate to a different page and come back to the Krispy Kreme login page, the reference to that element will become "stale," so you will need call the line above again.

    Whenever you need to preform an action (like click/submit) on that button you can use:

    submitButton.Click();
    

    or

    submitButton.Submit();
    

    If you would like output info in the form of a string, you could do the following:

    string buttonText = submitButton.Text; //output the text on the button
    string elementTypeAttribute = submitButton.getAttribute("type"); //outputs an html attribute of the element
    string elementTagName = submitButton.TagName; 
    

    I can't tell why your code is not working in the if statement from the information you've given. If you provide a code snippet then I can help. It sounds like you are trying to use the element as part of a conditional statement. If that is true, try using the methods above or using submitButton.ToString()



Suggested Topics