在我的一些Selinium Webdriver测试中,我注意到我无法通过对表单的任何元素调用submit()
来提交表单,但我可以在提交按钮上调用click()
。我创建了一个简单的测试网页来说明这个问题。在下面的示例中,当我调用submit()
时,我会看到提交按钮。但当我调用click()
时,表单实际上已经提交,我看到"已提交"。
<html>
<body>
<?php if(isset($_POST["submit"])): ?>
Submitted
<?php else: ?>
<form method="post">
<input id="submit" name="submit" type="submit" value="submit">
</form>
<?php endif; ?>
</body>
</html>
我正在使用这个Selenium模板,下面是我的测试外观:
@Listeners(ScreenshotListener.class)
public class LoginTest extends SeleniumBase {
@Test
public void test() {
WebDriver driver = getDriver();
driver.get("http://localhost/test.php");
WebElement submit = driver.findElement(By.id("submit"));
submit.click(); // works
// submit.submit(); // doesn't work
}
}
好吧,我也有类似的问题,我想分享一个迄今为止一直为我服务的解决方案。在某些网页上,我必须使用.Submit()
,在某些网页中,我必须在按钮元素上使用.Click()
。我必须使用.Click()
的页面会告诉我输入的用户名或密码不正确;尽管如此,如果我省略了.Submit()
部分并手动单击,它会使用程序填写的凭据登录。所以,我不得不根据它的id找到它的按钮元素,并在上面使用.Click()
。第二个网站的行为完全相反,当.Click()
在按钮上使用时,它什么也不做。相反,.Submit()
起作用。
所以,为了绕过这整个混乱,直到我弄清楚为止(我已经努力了一段时间),以下是我所做的。大多数网站都会在Enter
按下键事件上执行提交,所以,我就是这么做的。
以下是我的代码片段:
private void Login(string url, string usernameElement, string username,
string passwordElement, string password)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl(url);
IWebElement query = driver.FindElement(By.Id(usernameElement));
query.SendKeys(username);
query = driver.FindElement(By.Id(passwordElement));
query.SendKeys(password);
query.SendKeys(Keys.Enter); // simulates Enter key down to submit
}
这个小小的改变使我头疼不已。我已经在其他几个网站上测试过了,到目前为止没有任何问题。我知道这不是库问题的完全修复,但它是修复。