You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python Selenium WebDriver捕获动态更新的下载进度百分比数据

问题根源

你的代码仅在点击进度触发按钮后获取了1次进度元素的文本,没有持续监听元素的动态更新,因此只能捕获到初始的0%数值。

进度展示截图

调整后可直接运行的代码

from selenium import webdriver
import time
from selenium.webdriver.common.by import By

# 路径前加r避免Windows系统下转义字符异常
driver = webdriver.Chrome(executable_path=r"C:\chromedriver")
driver.get("https://www.seleniumeasy.com/test/")
driver.maximize_window()
time.sleep(5)
driver.find_element(By.XPATH, "//a[text()='No, thanks!']").click() 
driver.execute_script("window.scrollTo(300, 500)")
driver.find_element(By.XPATH, "//a[contains(text(),'& Sliders')]").click()
driver.find_element(By.LINK_TEXT, "Bootstrap Progress bar").click()
driver.find_element(By.XPATH, "//button[@id='cricle-btn']").click()

# 进度采集核心逻辑
percentage_list = []
last_percent = ""
# 配置30秒超时防止页面异常时程序卡死
wait_timeout = 30
start_time = time.time()

while time.time() - start_time < wait_timeout:
    current_percent = driver.find_element(By.CLASS_NAME, "percenttext").text
    # 仅当进度更新时才记录,避免生成重复数据
    if current_percent != last_percent:
        percentage_list.append(current_percent)
        print(f"当前捕获进度:{current_percent}")
        last_percent = current_percent
        # 进度到100%直接退出循环
        if "100%" in current_percent:
            break
    # 每0.2秒查询一次,可根据进度更新速度自行调整间隔
    time.sleep(0.2)

# 打印全部捕获的进度序列
print("全部进度数据:", percentage_list)

time.sleep(2)
driver.close()

核心调整点

  • 新增循环持续查询进度元素的文本内容,直到进度到100%或者触发超时为止
  • 增加去重判断,仅当进度值发生变化时才存入列表,避免生成大量无效重复数据
  • 增加超时机制,防止页面进度加载异常时程序无限等待
  • 替换为By类的元素定位写法适配所有版本Selenium,删除了原代码中未使用的冗余导入

内容的提问来源于stack exchange,提问作者Anshul Thakur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:42:01