1
<input id="password" name="password" maxlength="500" size="18" autocomplete="off" type="password">

<input id="passcode" name="password" maxlength="6" size="18" autocomplete="off" type="text">

I want to find if password textfield exist then enter "myPassword" otherwise if passcode textfield exist then enter "myPassCode" else throw exception.

if input id "password" exist then enter "mytext" otherwise
else if input id "passcode" exist then enter  "myPassCode"
else throw exception (missing password,passcode text fields)

Must be a better way to do it then this???? (bad code) :(

        try

        {

            driver.FindElement(By.Id("password")).SendKeys("myPassword");

        }

        catch (Exception ex)

        {

            try

            {

                driver.FindElement(By.Id("passcode")).SendKeys("myPassCode");

            }

            catch (Exception ex)

            {



            }

        }
001
  • 62,807
  • 94
  • 230
  • 350
  • 1
    You should check element exist first. E.g.: driver.FindElements(), then check size(), if size() > 0 -> element exists -> sendKeys – Nguyen Vu Hoang Jul 25 '14 at 02:41
  • It will throw an exception, -this will throw an exception----> var passwordFieldElement = driver.FindElement(By.Id("password")); – 001 Jul 25 '14 at 03:39
  • 1
    I used FindElements (with s in the end) :) – Nguyen Vu Hoang Jul 25 '14 at 03:43
  • Yep, I just found that answer here http://stackoverflow.com/questions/7991522/selenium-webdriver-test-if-element-is-present thanks :) – 001 Jul 25 '14 at 03:47

1 Answers1

1

use List<IWebElement> passwordElements = driver.FindElements(By.Id("password")). If passwordElements has more than 0 items in it, you can use it. If none were found you can check your other type, and then call SendKeys appropriately.

gudatcomputers
  • 2,822
  • 2
  • 20
  • 27
  • Maybe this IWebElement passwordElements = driver.FindElement(By.Id("password"));? – 001 Jul 25 '14 at 03:11
  • I don't think so. If I remember correctly, `FindElement` will throw `OpenQA.Selenium.NoSuchElementException : The element could not be found` when it doesn't find what it expects. `FindElements` will try to find some, and return an empty `List` if none are found. I don't have Visual Studio in front of me where I can look at the tests I've written that use this. I'll try to update once I'm in the office tomorrow morning. – gudatcomputers Jul 25 '14 at 03:13
  • this throws an exception :( var passwordFieldElement = driver.FindElement(By.Id("password")); – 001 Jul 25 '14 at 03:40
  • 1
    yes.. I'm saying call `FindElements` NOT `FindElement`. You need to call the one with 's' on the end that will return the collection type. – gudatcomputers Jul 25 '14 at 03:42
  • Yep, I just found that answer here http://stackoverflow.com/questions/7991522/selenium-webdriver-test-if-element-is-present thanks :) – 001 Jul 25 '14 at 03:46