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

Selenium页面加载时动态加载文本循环异常求助

Fixing the Looping Loading Animation in Selenium Thread

Let's break down why your current code stops after one full cycle and stays stuck on Loading...:

  1. Thread termination timing: When website_loaded = True is set, your loading thread is likely still in the final time.sleep(0.5) call after writing Loading.... Once the sleep finishes, the loop exits immediately, leaving the last printed state lingering on the console.
  2. Unclean console output: Since each subsequent loading string is longer than the previous, when you loop back to Loading., the extra dots from Loading... aren't overwritten (the \r only moves the cursor to the start of the line, it doesn't erase existing characters beyond the new string's length).

Here's the revised code that fixes both issues, plus uses a thread-safe Event instead of a global boolean for better reliability:

import threading
import sys
from selenium import webdriver
import time

# Use a thread-safe Event instead of a raw global boolean
website_loaded = threading.Event()
driver = webdriver.Firefox(executable_path=r"C:\Users\Username\Documents\Python\geckodriver.exe")
# Fix: sys.argv[1:] returns a list — use sys.argv[1] for single URL, or join if handling multiple args
website = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"

def loading():
    while not website_loaded.is_set():
        # Add trailing spaces to overwrite longer previous loading states
        sys.stdout.write("Loading.   \r")
        sys.stdout.flush()
        # Wait with timeout to check if page loaded early
        if website_loaded.wait(0.5):
            break
        
        sys.stdout.write("Loading..  \r")
        sys.stdout.flush()
        if website_loaded.wait(0.5):
            break
        
        sys.stdout.write("Loading... \r")
        sys.stdout.flush()
        if website_loaded.wait(0.5):
            break
    # Clear the loading line and print completion message
    sys.stdout.write("Page loaded successfully!          \n")
    sys.stdout.flush()

loading_thread = threading.Thread(target=loading)
loading_thread.start()

try:
    driver.get(website)
finally:
    # Ensure event is set even if page loading fails
    website_loaded.set()
    loading_thread.join()  # Wait for loading thread to clean up console

Key improvements in this code:

  • Thread-safe state management: threading.Event is purpose-built for inter-thread communication, making it far more reliable than a raw boolean variable.
  • Early loop exit: Using website_loaded.wait(0.5) instead of time.sleep(0.5) lets the loading thread exit immediately when the page finishes loading, no need to wait out the full sleep duration.
  • Clean console output: Trailing spaces in each loading string ensure longer previous states are fully overwritten, so you won't have leftover dots.
  • Error-safe cleanup: The try/finally block guarantees the event is set even if there's an error loading the page, and we join the thread to make sure it finishes cleaning up the console before the program exits.
  • Fixed URL handling: Corrected the sys.argv usage to properly capture a single URL (adjust to ' '.join(sys.argv[1:]) if you need to handle URLs with spaces).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:47:01