Python爬虫之Selenium设置元素等待的方法

来自:互联网
时间:2021-01-13
阅读:

一、显式等待

WebDriverWait类是由WebDirver 提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常(TimeoutException)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')

element = WebDriverWait(driver, 5, 0.5).until(
      EC.presence_of_element_located((By.ID, "kw"))
      )
element.send_keys('selenium')
time.sleep(5)

driver.quit()

语法:

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None).until(method, message=‘')

参数说明如下:

driver:浏览器驱动 timeout:最长超时时间,默认以秒为单位 poll_frequency:检测的间隔时间,默认为0.5s ignored_exceptions:超时后的异常信息,默认情况下抛NoSuchElementException异常 until(method, message=‘'):调用该方法提供的驱动程序作为一个参数,直到返回值为True until_not(method, message=‘'):调用该方法提供的驱动程序作为一个参数,直到返回值为False presence_of_element_located():判断元素是否存在。

二、隐式等待

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time

driver = webdriver.Chrome()

# 设置隐式等待为5秒
driver.implicitly_wait(5)
driver.get("http://www.baidu.com")

try:
 print(time.strftime('%Y-%m-%d %H:%M:%S'))
 driver.find_element_by_id("123456").send_keys('selenium') #不存在的id,看输出报错和时间
 # driver.find_element_by_id("kw").send_keys('selenium') # 存在的id
except NoSuchElementException as e:
 print(e)
finally:
 print(time.strftime('%Y-%m-%d %H:%M:%S'))
 driver.quit()

implicitly_wait() 默认0,参数的单位为秒,上边设置的等待时间为5秒,这个时间不像time.sleep(5)那样直接睡5秒;当执行流程到某个元素定位时,如果元素可以定位,则继续执行;如果元素定位不到,则它将以循环的方式不断地判断元素是否被定位到。比如说在1秒的时候定位到了,那么直接向下运行如果超出设置时长,则抛出异常。

返回顶部
顶部