①動態id定位不到元素
WebElement_xiexin_element = driver.find_element(By.xpath("//span[contains(.,'寫 信')]")) # WebElement_xiexin_element = driver.findElement(By.id("_mail_component_82_82")) xiexin_element.click()
上述代碼注釋掉的語句為通過id定位元素,但是此id“_mail_component_82_82”后面的數字會隨着你每次登陸而變化,即元素的id此時是動態可變化的,此時就無法通過id准確定位到元素。
所以推薦使用xpath的相對路徑方法查找到該元素。
②iframe框架原因定位不到元素
由於需要定位的元素可能在某一個frame框架里邊,所以有時通過單獨的id/name/xpath還是定位不到此元素。
<iframe id="left_frame" scrolling="auto" frameborder="0" src="index.php?m=Index&a=Menu" name="left_frame" noresize="noresize" style="height: 100%;visibility: inherit; width: 100%;z-index: 1"> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <body class="menuBg"> <div id="menu_node_type_0"> <table width="193" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <tr> <td id="c_1"> <table class="menuSub" cellspacing="0" cellpadding="0" border="0" align="center"> <tbody> <tr class="sub_menu"> <td> <a href="index.php?m=Coupon&a=SearchCouponInfo" target="right_frame">密碼重置</a> </td> </tr>
原本可以通過 element = driver.findElement(By.linkText("密碼重置")) 來定位此元素,但是由於該元素在iframe id="left_frame"這個frame里邊,所以需要先通過定位frame然后再定位frame里邊的某一個元素的方法定位此元素:
element =driver.switch_to.frame("left_frame").find_element(By.linkText("密碼重置"))
③不在同一個frame框架里邊查找元素
舉例:
一個web頁面,頁面左邊一欄屬於left_frame,右側屬於right_frame,此時如果當前處在left_frame,就無法通過id定位到right_frame的元素。
此時需要通過以下語句切換到默認的也是最外層的iframe
driver.switch_to.default_content()
④xpath描述錯誤
這個是因為在描述路徑的時候沒有按照xpath的規則來寫,造成找不到元素的情況出現
⑤點擊速度過快 頁面沒有加載出來就需要點擊頁面上的元素
⑥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."); }