selenium中的三种等待
时间: 2024-04-24 19:19:59 浏览: 22
selenium中有三种常用的等待方式,分别是隐式等待、显式等待和固定等待。
1. 隐式等待:使用隐式等待可以在查找元素时设置一个最大等待时间,如果在规定时间内找到了元素,则立即执行后续操作;如果超过了最大等待时间仍未找到元素,则抛出NoSuchElementException异常。隐式等待是全局性的,对整个WebDriver的生命周期都起作用。
```python
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) # 设置隐式等待时间为10秒
driver.get("https://www.example.com")
element = driver.find_element_by_id("myElement") # 在10秒内查找id为myElement的元素
```
2. 显式等待:使用显式等待可以在特定条件满足时等待一段时间,然后再执行后续操作。可以根据需要设置等待的最大时间和轮询的时间间隔,并指定等待的条件。如果在最大等待时间内满足了条件,则立即执行后续操作;如果超过了最大等待时间仍未满足条件,则抛出TimeoutException异常。
```python
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
driver = webdriver.Chrome()
driver.get("https://www.example.com")
wait = WebDriverWait(driver, 10) # 设置显式等待时间为10秒
element = wait.until(EC.presence_of_element_located((By.ID, "myElement"))) # 在10秒内等待id为myElement的元素出现
```
3. 固定等待:固定等待是一种简单的等待方式,它会在执行后续操作之前暂停一段固定的时间。可以使用time模块的sleep函数来实现固定等待。
```python
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.example.com")
time.sleep(5) # 暂停5秒
element = driver.find_element_by_id("myElement") # 在暂停5秒后查找id为myElement的元素
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)