selenium 頁面常會因為頁面加載慢而出現element 不能被點擊到的情況,比如加載過程中出現遮罩,導致element 可見不可點。以下方法重寫click(),用隱式等待解決這個問題。
基本思路是以下這樣的。
private static void click(WebElement element) throws Exception { for (int i = 100; i > 0; i--) { try { element.click(); break; } catch (Exception e) { Thread.sleep(200); } } }
某位厲害的同學重寫了上面的代碼,加入了更加智能的判斷。
protected void click(WebElement element) throws Exception { boolean start = true; int loopCount = 0; do{ loopCount++; try { element.click(); LoggerManager.logInfo("在嘗試點擊了"+loopCount+"次之后,終於點中了這個小壞蛋。"); break; } catch (Exception e) { //如果是element不可點擊,就等待之后重試,如果拋出別的異常,就放棄,不等了。 if(e.getMessage().contains("not clickable")){ Thread.sleep(200); }else{ start=false; LoggerManager.logError("Click Failed: "+e.getMessage()); } } }while(start); }