python selenium
最近在学习python,要爬的页面元素是条件显示的,所以要一直循环的获取页面元素,但因元素还没展示出来,就会报NoSuchElementException: Message: no such element: Unable to locate element 的错误,而且抛出这个错的时间要很久,大概3、4秒
解决办法
使用 implicitly_wait() 隐私等待,针对这个元素进行等待时间设置,当在设置的时间内没有元素返回,就会抛出异常,这样就可以缩短时间,一直的监控该元素的出现
try:
pages_container.implicitly_wait(0.2) # 等待0.2秒
insure_price_text = pages_container.find_element_by_xpath("/html[1]/body[1]/div[4]/div[2]/span[2]").text
if insure_price_text in '已过报价' and car.bid_price == '':
car.bid_price = current_price
print('投标价' + car.bid_price)
except:
pass
拓展知识
webdriver类中有三个和时间相关的方法:
- set_page_load_timeout
用来设置页面完全加载的超时时间,当页面刚开始加载要很长时间时,可以用这个方法来中断,再做其他操作
- set_script_timeout
用来设置一个异步调用成功回调前,抛出异常
- implicitly_wait
用于解析对象超时时间设置