在 Selenium 中使用 XPath 在 HTML DOM 中找不到某個元素時,會引發哪種異常?
如果使用 xpath 在 HTML DOM 中找不到某個元素,則會引發 NoSuchElementException。當 WebDriver 嘗試定位某個在 DOM 中不存在的 Web 元素時,會引發此異常。如果我們為某個元素建立了不正確的 xpath,通常會遇到此異常。
下圖顯示了 NoSuchElementException 的示例。
示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class ElemntsText{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.tw/upsc_ias_exams.htm"); //identify an element with tagname WebElement e = driver.findElement(By.tagName("h2")); String str = e.getText(); driver.quit(); } }
輸出
廣告