要暂停网络驱动程序的执行毫秒,您可以传递number of seconds 或floating point number of seconds,如下所示:
import time
time.sleep(1) #sleep for 1 sec
time.sleep(0.25) #sleep for 250 milliseconds
但是,在使用 Selenium 和 WebDriver 进行 Automation 时,使用 time.sleep(secs) 而没有任何特定条件实现 违背了自动化的目的,应该不惜一切代价避免。根据文档:
time.sleep(secs) 将当前线程的执行挂起给定的秒数。该参数可以是一个浮点数,以指示更精确的睡眠时间。实际的挂起时间可能少于请求的时间,因为任何捕获的信号都会在执行该信号的捕获例程后终止 sleep()。此外,由于系统中其他活动的调度,暂停时间可能比请求的时间长。
因此根据讨论而不是time.sleep(sec),您应该使用WebDriverWait() 与expected_conditions() 结合使用来验证元素的状态,三个广泛使用的expected_conditions 如下:
presence_of_element_located
presence_of_element_located(locator) 定义如下:
class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)
Parameter : locator - used to find the element returns the WebElement once it is located
Description : An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible or interactable (i.e. clickable).
visibility_of_element_located
visibility_of_element_located(locator) 定义如下:
class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)
Parameter : locator - used to find the element returns the WebElement once it is located and visible
Description : An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.
element_to_be_clickable
element_to_be_clickable(locator) 定义如下:
class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)
Parameter : locator - used to find the element returns the WebElement once it is visible, enabled and interactable (i.e. clickable).
Description : An Expectation for checking an element is visible, enabled and interactable such that you can click it.
参考
您可以在WebDriverWait not working as expected找到详细讨论