c# Selenium Webdriver - 元素隐藏 - "Element is not currently visible and so may not be interacted with"

c# Selenium Webdriver - Element Hidden - "Element is not currently visible and so may not be interacted with"

我有一个关于文本框的问题,我似乎无法让 selenium 单击并输入文本。这是一个网站的密码框。用户名部分很好,但无论出于何种原因,我都无法将文本发送到密码框。我收到错误消息 "Element is not currently visible and so may not be interacted with"

我尝试了几种不同的方法来定位文本框,例如 XPath 名称、包含、id 等,但似乎没有任何效果。有任何想法吗?我也尝试过等待和等待元素。我还返回了所有元素名称 "tbPassword" 以查看是否存在冲突并且它只有 returns 1.

这是我的代码:

driver.Navigate().GoToUrl("http://www.paddypower.com/bet");

        IWebElement clickUsername = driver.FindElement(By.XPath("//input[@name='tbUsername']"));
        clickUsername.Click();
        clickUsername.SendKeys("MyUsername");


        IWebElement clickPassword = driver.FindElement(By.XPath("//input[@name='tbPassword']"));
        clickPassword.Click();
        clickPassword.SendKeys("Mypassword");

有一个重复的密码input实际可见:

<div class="inputbg">
    THIS IS VISIBLE => <input id="dummypassword" class="input" type="text" onfocus="this.style.display='none';document.getElementById('pw').style.display='inline';document.getElementById('pw').focus()" value="Password" tabindex="2" name="dummypassword">
    THIS IS INVISIBLE => <input id="pw" class="input" type="password" onblur="if(this.value==''){this.style.display='none';document.getElementById('dummypassword').style.display='inline'}" onkeypress="if (event.keyCode==13)fmLogin.submit();" value="" style="display: none;" tabindex="2" name="tbPassword" autocomplete="off">
</div>

单击可见的 "dummy" 输入后,它将变为不可见,而 "tbPassword" 输入变为可见。在您的代码中遵循此行为:

IWebElement clickPassword = driver.FindElement(By.Id("dummypassword"));
clickPassword.Click();

IWebElement realPasswordInput = driver.FindElement(By.XPath("//input[@name='tbPassword']"));
realPasswordInput.SendKeys("Mypassword");

我也遇到了同样的问题,当我看到这个 post 它帮助我找出了真正的问题,但在我的例子中有两个同名的控件 "username" 和 "password" 并且当我想在找到控件后使用 control.SendKeys 时系统抛出异常,所以我使用下面的代码来解决这个问题。

allTextBoxes = driver.FindElements(By.Id("username"));
        var allPasswordTextBoxes = driver.FindElements(By.Id("password"));

        var userNameTextField = allTextBoxes.Count > 0 ? allTextBoxes[1] : allTextBoxes[0];
        userNameTextField.SendKeys("myUsername");

        var passwordTextField = allPasswordTextBoxes.Count > 0 ? allPasswordTextBoxes[1] : allPasswordTextBoxes[0];
        passwordTextField.SendKeys("myPassword");