selenium循环判断元素出现后执行动作
时间: 2023-10-06 09:04:27 浏览: 48
如果您想在 Selenium 中循环判断元素是否出现,并在元素出现后执行某个动作,可以使用 Python 中的 while 循环结合 try-except 语句块和条件判断语句。例如,以下代码会不断循环检查页面上的某个元素是否出现,如果元素出现则执行某个动作:
```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/")
# 设置最大等待时间为 10 秒
wait = WebDriverWait(driver, 10)
# 定义目标元素的选择器
target_selector = (By.ID, "my-element-id")
# 使用 while 循环判断元素是否出现
while True:
# 等待目标元素出现
try:
target_element = wait.until(EC.presence_of_element_located(target_selector))
except:
# 如果元素未出现,则继续循环等待
continue
# 如果元素已出现,则执行某个动作
print("目标元素已出现!")
# 在此处添加您要执行的动作
# 退出循环
break
```
在上述代码中,我们首先定义了目标元素的选择器(在本例中为 ID 为 "my-element-id" 的元素)。然后,我们使用 while 循环不断执行 try-except 语句块,直到目标元素出现为止。在 try 语句块中,使用 `wait.until()` 方法等待目标元素出现,如果元素未出现则抛出异常,在 except 语句块中进行捕获并继续循环等待。当目标元素被找到后,程序会执行某个动作(在本例中为打印一条消息),然后使用 break 语句退出循环。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)