自動化測試中經常會出現無法定位元素的情況,報selenium.common.exceptions.NoSuchElementException錯誤
1.動態id定位不到元素
for example:
//WebElement xiexin_element = driver.findElement(By.id("_mail_component_82_82"));
WebElement xiexin_element = driver.findElement(By.xpath("//span[contains(.,'寫 信')]"));
xiexin_element.click();
上面一段代碼注釋掉的部分為通過id定位element的,但是此id“_mail_component_82_82”后面的數字會隨着你每次登陸而變化,此時就無法通過id准確定位到element。
所以推薦使用xpath的相對路徑方法查找到該元素。
2.Frame/Iframe原因定位不到元素:
1 #coding:utf-8 2 3 from selenium import webdriver 4 import time 5 driver = webdriver.Firefox() 6 driver.get('http://mail.163.com/') 7 8 #獲得當前163郵箱窗口 9 nowhandle = driver.current_window_handle 10 driver.implicitly_wait(30) 11 driver.switch_to_frame('x-URS-iframe') #內嵌了一個iframe 12 13 #打開注冊頁面 14 driver.find_element_by_id('changepage').click() 15 #獲得所有窗口 16 all_handles = driver.window_handles 17 18 #遍歷handles 判斷是否為當前窗口 19 for handle in all_handles: 20 if handle !=nowhandle: 21 driver.switch_to_window(handle) 22 print '注冊窗口' 23 #driver.find_element_by_id('changepage').click() 24 #driver.close() #關閉注冊頁 25 26 #回到原來的窗口 27 time.sleep(10) 28 driver.switch_to_window(nowhandle)
3.xpath描述錯誤
這個是因為在描述路徑的時候沒有按照xpath的規則來寫 造成找不到元素的情況出現。
4.點擊速度過快 頁面沒有加載出來就需要點擊頁面上的元素
這個需要增加一定等待時間,顯示等待時間可以通過WebDriverWait 和util來實現
例如:
//用WebDriverWait和until實現顯示等待 等待歡迎頁的圖片出現再進行其他操作
WebDriverWait wait = (new WebDriverWait(driver,10));
wait.until(new ExpectedCondition<Boolean>(){
public Boolean apply(WebDriver d){
boolean loadcomplete = d.switchTo().frame("right_frame").findElement(By.xpath("//center/div[@class='welco']/img")).isDisplayed();
return loadcomplete;
}
});
也可以自己預估時間通過Thread.sleep(5000);//等待5秒 這個是強制線程休息.
5.firefox安全性強,不允許跨域調用出現報錯
錯誤描述:uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location:
解決辦法:
這是因為firefox安全性強,不允許跨域調用。
Firefox 要取消XMLHttpRequest的跨域限制的話,第一
是從 about:config 里設置 signed.applets.codebase_principal_support = true; (地址欄輸入about:config 即可進行firefox設置)
第二就是在open的代碼函數前加入類似如下的代碼: try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("Permission UniversalBrowserRead denied."); }