如何让 Python 中的 Selenium WebDriver 休眠几毫秒

新手上路,请多包涵

我在脚本中使用 time 库:

 import time
time.sleep(1)

它可以让我的 Selenium WebDriver 休眠一秒钟,但怎么可能休眠 250 毫秒呢?

原文由 AliRehman7141 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
2 个回答

要将 webdriver 的执行暂停 几毫秒,您可以传递 number of secondsfloating point number of seconds 如下:

 import time
time.sleep(1) #sleep for 1 sec
time.sleep(0.25) #sleep for 250 milliseconds

但是,在使用 time.sleep(secs)SeleniumWebDriver 用于 自动化 时,如果没有任何 特定条件来实现 自动化,则应不惜一切代价避免。根据文档:

time.sleep(secs) 将当前线程的执行暂停给定的秒数。该参数可以是一个浮点数,以指示更精确的睡眠时间。实际暂停时间可能比请求的时间短,因为任何捕获的信号都会在执行该信号的捕获例程后终止 sleep()。此外,由于系统中其他活动的调度,暂停时间可能比请求的任意时间长。


因此,根据讨论而不是 time.sleep(sec) 你应该使用 WebDriverWait() 结合 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 中找到详细的讨论

原文由 undetected Selenium 发布,翻译遵循 CC BY-SA 4.0 许可协议

time.sleep() 采用浮点参数:

 time.sleep(0.25)

文档(它们值得一读,尤其是因为它们解释了睡眠最终可能比预期更短或更长的条件)。

原文由 NPE 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题