SeleniumWebdriver - 驱动程序找到元素但无法处理它?

时间:2016-03-18 05:29:26

标签: selenium

我正在尝试进行一项简单的测试来测试网站的登录表单。当我初始化元素Selenium找到它但是如果我尝试点击它或检查它的显示我是否得到一个异常,该元素不可见或False为显示。

页面:http://www.officemate.co.th/

我的代码:

    IWebDriver driver = new ChromeDriver();
    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
    driver.Navigate().GoToUrl("http://www.officemate.co.th");

    IWebElement openSignUp = driver.FindElement(By.CssSelector("body > div:nth-child(6) > div > div:nth-child(3) > ul > li.dropdown > a"));
    openSignUp.Click();

    IWebElement usernameField = driver.FindElement(By.Id("UserId"));

    usernameField.SendKeys("SomeUser");
    Console.WriteLine(usernameField.Displayed);

1 个答案:

答案 0 :(得分:0)

尝试以下代码。我测试过它工作正常。

try
        {
            ChromeDriver driver = new ChromeDriver(@"C:\Users\Muhammad USman\Downloads\chromedriver_win32");
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
            //now i changed path for login.
            driver.Navigate().GoToUrl("https://www.officemate.co.th/Account/Login");


            //full specified xPath of eache element. is here whihc i'll use know.
            //https://www.officemate.co.th/Account/Login
            var email = @"/html/body/div[9]/div/fieldset/form/div[1]/div/input";
            var password = @"/html/body/div[9]/div/fieldset/form/div[2]/div/input";
            var check = @"/html/body/div[9]/div/fieldset/form/div[3]/div/input[1]";
            var login = @"/html/body/div[9]/div/fieldset/form/div[4]/div/button";


            IWebElement usernameField = driver.FindElement(By.XPath(email));
            usernameField.Clear();
            usernameField.SendKeys("SomeUser@gmail.com");
            Console.WriteLine(usernameField.Displayed);

            IWebElement pass = driver.FindElement(By.XPath(password));
            pass.Clear();
            pass.SendKeys("Some!password");

            //Check box
            var checkBox = driver.FindElement(By.XPath(check));
            if (!checkBox.Selected)
            {
                checkBox.Click();
            }

            driver.FindElement(By.XPath(login)).Click();

            if (driver.FindElements(By.XPath("/html/body/div[9]/div/fieldset/form/div[1]/p")).Count > 0)
            {
                //invalid login error message
                var errorMessage = driver.FindElement(By.XPath("/html/body/div[9]/div/fieldset/form/div[1]/p")).Text;
            }
        }
        catch (Exception exp)
        {

            throw;
        }

如果有任何问题,请告诉我。 感谢。