1

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();

                    }
                }
Night
  • 47
  • 5
  • It's throwing that exception because you're attempting to find that element in your if statement. You need to try to find the element and then catch the exception or else it will stop execution. – user2272115 Jun 03 '16 at 19:26
  • You should check first if the element exists. [Here](http://stackoverflow.com/questions/7991522/selenium-webdriver-test-if-element-is-present) you may find how to do it – Jhon Jun 03 '16 at 19:28

1 Answers1

1

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();
Gilles
  • 5,269
  • 4
  • 34
  • 66