selenium自動化頁面元素不存在異常發生的緣由有一下幾點:java
(1)頁面加載時間過慢,須要查找的元素程序已經完成可是頁面還未加載成功。此時能夠加載頁面等待時間。web
(2)查到的元素沒有在當前的iframe或者frame中。此時須要切換至對應的iframe或者frame中才行。chrome
(3)元素錯誤。瀏覽器
解決頁面加載時間所引發的元素找不到,咱們能夠爲頁面設置加載時間。時間的設置分爲如下三種:app
(1)顯式等待異步
顯示等待是針對於某個特定的元素設置的等待時間,若是在規定的時間範圍內,沒有找到元素,則會拋出異常,若是在規定的時間內找到了元素,則直接執行,即找到元素就執行相關操做。ide
public static void main(String[] args) throws IOException {函數
System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
ChromeOptions Options = new ChromeOptions();
Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data");
WebDriver driver = new ChromeDriver(Options);
try {post
WebDriverWait wait = new WebDriverWait(driver, 10, 1);
// 每隔1秒去調用一下until中的函數,默認是0.5秒,若是等待10秒尚未找到元素 。則拋出異常。
wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
driver.findElement(By.id("kw"));
return driver.findElement(By.id("kw"));
}
}).sendKeys("我是一個自動化測試小腳本");
} finally {
driver.close();
Runtime.getRuntime().exec("taskkill /F /im " + "chromedriver.exe");
Runtime.getRuntime().exec("taskkill /F /im " + "chrome.exe");
}
}
(2)隱式等待
隱式等待是設置的全局等待,分爲一、頁面加載超時等待 ;二、頁面元素加載超時;三、異步腳本超時
若是是頁面元素超時,設置等待時間,是對頁面中的全部元素設置加載時間。隱式等待是其實能夠理解成在規定的時間範圍內,瀏覽器在不停的刷新頁面,直到找到相關元素或者時間結束。
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
ChromeOptions Options = new ChromeOptions();
Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data");
WebDriver driver = new ChromeDriver(Options);
try {
//頁面加載超時時間設置爲5s
driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
driver.get("https://www.baidu.com/");
//定位對象時給10s 的時間, 若是10s 內還定位不到則拋出異常
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("kw")).sendKeys("隱式等待");
//異步腳本的超時時間設置成3s
driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
} finally {
driver.close();
Runtime.getRuntime().exec("taskkill /F /im " + "chromedriver.exe");
Runtime.getRuntime().exec("taskkill /F /im " + "chrome.exe");
}
}
(3)線程等待
線程等待是java語言中的線程類Thread類中的sleep()方法。此等待是很死板的,須要等待時間結束纔會執行相關代碼。該方法須要拋出InterruptedException 異常。通常不建議使用,可是在彈窗處理,能夠優先選擇線程等待。
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
ChromeOptions Options = new ChromeOptions();
Options.addArguments("user-data-dir=C:\\Users\\happy\\AppData\\Local\\Google\\Chrome\\User Data");
WebDriver driver = new ChromeDriver(Options);
try {
Thread.sleep(5000);driver.findElement(By.id("kw")).sendKeys("線程等待");} finally {driver.close();Runtime.getRuntime().exec("taskkill /F /im " + "chromedriver.exe");Runtime.getRuntime().exec("taskkill /F /im " + "chrome.exe");}}