Home >Backend Development >Python Tutorial >How Can I Precisely Sleep in Selenium WebDriver Using Python, and What Are Better Alternatives to `time.sleep()`?

How Can I Precisely Sleep in Selenium WebDriver Using Python, and What Are Better Alternatives to `time.sleep()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 22:21:29178browse

How Can I Precisely Sleep in Selenium WebDriver Using Python, and What Are Better Alternatives to `time.sleep()`?

Sleeping Selenium WebDriver in Python for Milliseconds

While the time library provides time.sleep(sec) for suspending execution, achieving precision of 250 milliseconds requires specifying a fractional number of seconds:

import time
time.sleep(0.25) # Sleep for 250 milliseconds

However, excessive use of time.sleep(sec) is discouraged in Selenium WebDriver automation, as it can hinder efficiency.

Alternatives to time.sleep()

Instead, consider using WebDriverWait() in conjunction with expected_conditions(). Three commonly used conditions include:

presence_of_element_located:

  • Aims to locate an element on the DOM, regardless of visibility or interactivity.

visibility_of_element_located:

  • Checks if an element is present, visible, and has a non-zero height and width.

element_to_be_clickable:

  • Ensures an element is visible, enabled, and interactable, allowing for clicks.

How to Use WebDriverWait()

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "my_button")))

This example waits for up to 10 seconds for the element with the ID "my_button" to become clickable before continuing.

Reference

  • [WebDriverWait Not Working as Expected](https://stackoverflow.com/questions/39294435/webdriverwait-not-working-as-expected)

The above is the detailed content of How Can I Precisely Sleep in Selenium WebDriver Using Python, and What Are Better Alternatives to `time.sleep()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn