操作系统:Windows 7 32位 Chrome驱动程序版本:2.30 Selenium Webdriver 版本:3.4.0 Java 8
我尝试了几种不同的方法来清理此代码,而不必重复相同的 try/catch block 。我正在尝试检查我正在测试的页面上是否存在各种元素。我可以优雅地向控制台报告,并且此代码确实可以正常工作。 我遇到的问题是代码不优雅。有没有办法嵌套这些 try/catch block ,或者将它们放入 if/else 循环中?
try {
driver.findElement(By.xpath("/html/head/title"));
System.out.println("Title found...");
Thread.sleep(1000);
} catch (NoSuchElementException ex) {
System.out.println("Title NOT FOUND...");
// ex.printStackTrace();
}
try {
driver.findElement(By.xpath("//*[@id='logindiv']"));
System.out.println("Login form found...");
Thread.sleep(1000);
} catch (NoSuchElementException ex) {
System.out.println("Login form NOT FOUND...");
// ex.printStackTrace();
}
try {
driver.findElement(By.id("username"));
System.out.println("'Username' field found...");
Thread.sleep(1000);
} catch (NoSuchElementException ex) {
System.out.println("'Username' form NOT FOUND...");
// ex.printStackTrace();
}
try {
driver.findElement(By.id("password"));
System.out.println("'Password' field found...");
Thread.sleep(1000);
} catch (NoSuchElementException ex) {
System.out.println("'Password' form NOT FOUND...");
// ex.printStackTrace();
}
try {
driver.findElement(By.id("loginSubmit")).getText();
System.out.println("Login button found...");
Thread.sleep(1000);
} catch (NoSuchElementException ex) {
System.out.println("Login button NOT FOUND...");
// ex.printStackTrace();
}
最佳答案
一些事情...
我坚信异常应该是异常的,这意味着异常不应该被用作流程控制。这得到进一步支持by the docs ,
findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
所以你应该替换
.findElement()
和try-catch
与.findElements()
并测试是否为空。请参阅 #2 中的示例。你真的应该使用一些
Assert
像 JUnit 等库。它使这些验证变得更加容易/干净。这整件事
try { driver.findElement(By.id("username")); System.out.println("'Username' field found..."); Thread.sleep(1000); } catch (NoSuchElementException ex) { System.out.println("'Username' form NOT FOUND..."); // ex.printStackTrace(); }
应该/可能看起来像
Assert.assertFalse(driver.findElements(By.id("username")).isEmpty(), "Validate Username field exists");
有人可能会说它更快,等等,但是……看到人们使用像 XPath 这样复杂的东西除了通过 ID 定位元素之外,这让我很伤心,例如
By.xpath("//*[@id='logindiv']")
。这更简单,更容易阅读,如By.id("logindiv")
.您可以通过谷歌搜索来查看所有详细信息,但
Thread.Sleep()
除外。这是一种不好的做法,应该避免。而是使用WebDriverWait
。探索ExpectedConditions
查看所有可以等待的内容并自由地使用它。在您在代码中发布的情况下,我看不出有任何理由等待其中任何一个,因此这会浪费几秒钟不必要的时间。你的最后一个例子是拉
.getText()
但不使用它。由于您只是检查该按钮是否存在,因此您可以安全地删除.getText()
从最后开始。
关于java - Selenium 网络驱动程序(Java): How can I nest these NoSuchElement Exception tests?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021807/