Home > Software design >  C# Seleniıum Iweb elements css selector
C# Seleniıum Iweb elements css selector

Time:06-14

I am checking email on a website with c# selenium, if you have an email and if there is no email, adding class

Html

<div >
 <span ></span>
</div>

Code

IWebDriver driver = new ChromeDriver();
for (int i = 0; i < Convert.ToInt32((mailCount.Text)); i  )
{
    string email = helper.RastgeleKelime();
    driver.Navigate().GoToUrl("https://www.xxxxxxx.com/accounts/emailsignup/");
    Thread.Sleep(2000);
    IWebElement username = driver.FindElement(By.Name("emailOrPhone"));
    IWebElement Fullname = driver.FindElement(By.Name("fullName"));
    username.SendKeys("[email protected]");
    Fullname.SendKeys("ssssss");
    Thread.Sleep(2000);

    IWebElement error = driver.FindElement(By.CssSelector("div.i24fI span.coreSpriteInputError"));
    if (error != null)
    {
        avMailList.Items.Add(email.ToString());
    }
    else
    {
        mailList.Items.Add(email.ToString());
    }
    Thread.Sleep(2000);

I check as above but

IWebElement error = driver.FindElement(By.CssSelector("div.i24fI span.coreSpriteInputError"));

If it doesn't exist, it gives an error because it can't find the element in its control.

CodePudding user response:

You can use FindElements to get a collection of IWebElement and check the value of the first element using FirstOrDefault() from Linq

using System.Linq

ReadOnlyCollection<IWebElement> errors = driver.FindElements(By.CssSelector("div.i24fI span.coreSpriteInputError"));
IWebElement error = errors.FirstOrDefault();

Now error will be IWebElement or null.

  • Related