Selenium 4 Python如何等待元素属性值并处理进度条?
实现进度条达到指定百分比后停止(Selenium 4)
针对你遇到的Selenium 4中attributeToBe()方法被弃用的问题,以下是两种可行的解决方案,以demoqa的进度条页面为例:
方法一:使用显式等待+Lambda表达式(推荐)
Selenium 4中ExpectedConditions.attributeToBe()已被标记为过时,可通过Lambda表达式自定义等待条件,实现等待进度条属性达到目标值后停止:
Java 示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class ProgressBarHandler { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://demoqa.com/progress-bar"); // 启动进度条 WebElement startStopBtn = driver.findElement(By.id("startStopButton")); startStopBtn.click(); // 定位进度条元素 WebElement progressBar = driver.findElement(By.className("progress-bar")); // 等待进度条aria-valuenow属性等于"70" new WebDriverWait(driver, Duration.ofSeconds(10)) .until(driverInstance -> progressBar.getAttribute("aria-valuenow").equals("70")); // 停止进度条 startStopBtn.click(); driver.quit(); } }
Python 示例
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Chrome() driver.get("https://demoqa.com/progress-bar") start_stop_btn = driver.find_element(By.ID, "startStopButton") start_stop_btn.click() progress_bar = driver.find_element(By.CLASS_NAME, "progress-bar") # 等待进度条属性值达到70 WebDriverWait(driver, 10).until( lambda d: progress_bar.get_attribute("aria-valuenow") == "70" ) start_stop_btn.click() driver.quit()
方法二:使用循环检查属性值
如果更倾向于直观的逻辑,可通过循环持续检查进度条的属性值,达到目标后执行停止操作:
Java 示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ProgressBarLoop { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://demoqa.com/progress-bar"); WebElement startStopBtn = driver.findElement(By.id("startStopButton")); WebElement progressBar = driver.findElement(By.className("progress-bar")); startStopBtn.click(); // 循环检查进度,直到达到70% while (true) { String currentProgress = progressBar.getAttribute("aria-valuenow"); if ("70".equals(currentProgress)) { startStopBtn.click(); break; } // 短暂休眠避免频繁占用资源 Thread.sleep(50); } driver.quit(); } }
Python 示例
from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get("https://demoqa.com/progress-bar") start_stop_btn = driver.find_element(By.ID, "startStopButton") progress_bar = driver.find_element(By.CLASS_NAME, "progress-bar") start_stop_btn.click() while True: current_progress = progress_bar.get_attribute("aria-valuenow") if current_progress == "70": start_stop_btn.click() break time.sleep(0.05) driver.quit()
两种方法均能实现需求:显式等待是Selenium官方推荐的方式,无需手动处理休眠逻辑;循环方式则更直观,适合简单场景。
内容的提问来源于stack exchange,提问作者Tanvir Ahmed
相关产品推荐
相关产品推荐

