自动化测试中经常会出现无法定位元素的情况,报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."); }
转载于:https://www.cnblogs.com/stephenmc/p/6187314.html
最后
以上就是稳重白云最近收集整理的关于Selenium中的webdriver定位元素失败的常见原因的全部内容,更多相关Selenium中内容请搜索靠谱客的其他文章。
发表评论 取消回复