我對帶有 selenium 的 java 很陌生,并且有一個關于 NoSuchElementException 的問題:
我得到了以下應該回傳 WebElement 的方法:
public WebElement getElementByXpath(String xpath, WebDriver driver) {
try {
System.out.println("Test");
return driver.findElement(By.xpath(xpath));
} catch (NoSuchElementException e) {
System.out.println("Element not found");
}
return null;
}
所以我想要的是,如果找不到元素,則只會列印“找不到元素”。但不是這個,我得到完整的錯誤訊息,但沒有“找不到元素”:
Test
2022-03-07 16:22:33.159 ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@id='sr_creg_country123']/option[contains(text(), 'Deutschland')]"}
(Session info: chrome=98.0.4758.80)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
.
.
.
據我了解,不會拋出例外,因為從未列印過訊息“找不到元素”?但是有人可以解釋我為什么以及我必須做什么才能執行catch-block中的代碼嗎?
干杯,邁克爾
uj5u.com熱心網友回復:
in有兩個NoSuchElementException例外Java,一個是 in ,一個是java.utilin org.openqa.selenium。為了捕獲WebDriver NoSuchElementException例外,您需要明確定義捕獲catch (org.openqa.selenium.NoSuchElementException e),如下所示:
public WebElement getElementByXpath(String xpath, WebDriver driver) {
try {
System.out.println("Test");
return driver.findElement(By.xpath(xpath));
} catch (org.openqa.selenium.NoSuchElementException e) {
System.out.println("Element not found");
}
return null;
}
或者,您可以匯入要使用的例外
import org.openqa.selenium.NoSuchElementException
這樣您的方法代碼可以保持不變:
import org.openqa.selenium.NoSuchElementException
public WebElement getElementByXpath(String xpath, WebDriver driver) {
try {
System.out.println("Test");
return driver.findElement(By.xpath(xpath));
} catch (NoSuchElementException e) {
System.out.println("Element not found");
}
return null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439675.html
