解决网页元素无法定位(NoSuchElementException: Unable to locate element)的几种方法

只解决一个问题--NoSuchElementException: Message: Unable to locate element

出错形式 

出错原因

1.可能元素加载未完成

元素加载没完成,同样的路径定位,每次测试结果确是不一样的,有时候抛出错误,有时候正常!这就比较蛋疼了,也就是说,和你的定位方法半毛钱关系没有,而很大程度上取决于你的电脑和网速!

1.解决方案A:添加两行代码

wait = ui.WebDriverWait(driver,10)
wait.until(lambda driver: driver.find_element_by_方法("定位路径自己来"))

 WebDriverWait(driver,10)的意思是;10秒内每隔500毫秒扫描1次页面变化,当出现指定的元素后结束。driver是前面操作webdriver.firefox()的句柄 
完整的小段代码是:

from selenium import webdriver
import selenium.webdriver.support.ui as uidriver_item=webdriver.Firefox()
url="https://movie.douban.com/"
wait = ui.WebDriverWait(driver_item,10)
driver_item.get(url)
wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div/div/label[5]"))
driver_item.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div/div/label[5]").click()

1.解决方案B:使用while+try…except结合

下面来个例子,完整的可运行代码如下:

from selenium import webdriver
import time
import osdriver_item=webdriver.Firefox()
url="https://movie.douban.com/"
driver_item.get(url)while 1:start = time.clock()try:driver_item.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div/div/label[5]").click()print '已定位到元素'end=time.clock()breakexcept:print "还未定位到元素!"print '定位耗费时间:'+str(end-start)

运行结果如下:

还未定位到元素!
已定位到元素
定位耗费时间:0.262649990301

分析

开启页面后,并不是元素都一次性加载完成的,依赖于网速和电脑,从B方法中可见,所耗费的时间,还有一种静态的方法就是我以前常用的sleep,一般睡一秒就够了,但是对于不同电脑不同网速的情况,建议还是使用动态方法,也就是A方法,以变应变!

从代码可读性上和效率上都是A方法比较好,更加符合python的特性,简洁优美,而B方法应该是我这样初学者自己能想到的一种方法,先得自己想解决方案,然后再参考现有方法,我感觉这样才有意义。

2.本身定位方法错误

这也就是最常见的了,也是最容易犯的错误,自己对元素定位方法不够熟练,就很容易错误了,所以多想想该怎么定位才最容易,我现在最喜欢的是用xpath方法定位,DOM树的结构挺清晰的,可能我还是新手的原因吧!

2.解决方案

多查询元素定位方法,多使用多熟练,吐槽一下正则。。。相比较正则,我还是更喜欢BeautifulSoup或者xpath来用,额。。。

比方说,我要看看BeautifulSoup到底规则效果怎么样,那我会单独写个测试模块
 

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
#find_all() 和 find() 只搜索当前节点的所有子节点,孙子节点等.
# find_parents() 和 find_parent() 用来搜索当前节点的父辈节点,
# 搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容html = """
The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were , Lacie and Tillie; and they lived at the bottom of a well.

...

"""soup=BeautifulSoup(html,"lxml") #soup=BeautifulSoup(open('index.html'),"lxml")#若本身有html文件,则打开#print soup.prettify() print soup.title print soup.a.string print soup.a['href'] print soup.a['class']

 

--------------------- 
作者:哈士奇说喵 
来源:CSDN 
原文:https://blog.csdn.net/mrlevo520/article/details/51954203 
版权声明:本文为博主原创文章,转载请附上博文链接!


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部