Night
Night

Reputation: 47

Selenium for each loop error

My for each loop gives me an error: no such element: Unable to locate element: {"method":"class name","selector":"invite_someone_failure"} I only want the loop to restart if its been displayed and then check for invite_someone_success but it has not been displayed yet and stops before it can restart loop. Also doesn't seem to refresh the page

                foreach (string line in File.ReadLines(@"C:\\extract\\in7.txt"))
            {
                if (line.Contains("@"))
                {
                    searchEmail.SendKeys(line);
                    submitButton.Click();
                    var result = driver.FindElement(By.ClassName("invite_someone_success")).Text;
                    using (StreamWriter writer = File.AppendText("C:\\extract\\out7.txt"))
                    {
                        writer.WriteLine(result + ":" + line);
                    }
                    var unfollowButton = driver.FindElement(By.ClassName("unfollow_button"));
                    unfollowButton.Click();

                    if (driver.FindElement(By.ClassName("invite_someone_failure")).Displayed) {
                    driver.Navigate().Refresh();

                    }
                }

Upvotes: 1

Views: 366

Answers (1)

Gilles
Gilles

Reputation: 5407

The error you are seeing is because Selenium can't find any element with the class invite_someone_failure.

When it can't find an element it throws an exception thus aborting the loop. This also explains why your page isn't refreshed as the code to refresh the page is after the exception happens.

Since you have an if statement I can guess you don't want an exception in driver.FindElement to abort your execution.

Try something like this:

var elements = driver.FindElements(By.ClassName("invite_someone_failure"));

if (elements.Any())
    driver.Navigate().Refresh();

Upvotes: 1

Related Questions