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

Python Threading无限循环定时获取币种价格仅显示一次问题求助

问题修复与代码改进

1. 解决只输出一次价格的问题

你的runA函数里写了return convert[0].text,这会让循环刚执行一次就直接退出函数,线程自然也就停了。直接删掉这个return,让while True能持续循环就行。另外没必要每次循环都重新调用driver.get(url),第一次打开页面后,后续直接刷新获取源码更高效。

2. 解决DeprecationWarning警告

Selenium 4.x已经弃用了executable_path参数,得改用Service类来指定chromedriver的路径。

3. 线程守护设置修正

原代码里t1.daemon只是访问属性,没赋值,要写成t1.daemon = True,这样主线程退出时子线程会跟着结束,不会残留进程。

改进后的完整代码

from threading import Thread
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 用Service类替代过时的executable_path参数
service = Service('/Applications/Python 3.10/chromedriver')
driver = webdriver.Chrome(service=service)

def runA():
    # 仅打开一次页面,减少重复加载开销
    url = 'https://www.binance.com/trade/BTC_USDT?theme=dark&type=spot'
    driver.get(url)
    time.sleep(3)  # 首次加载给足渲染时间
    
    while True:
        # 直接获取当前页面源码
        response = driver.page_source
        soup = BeautifulSoup(response, 'html.parser')
        convert = soup.findAll('div', {'class': 'subPrice'})
        
        if convert:  # 加个判断避免找不到元素报错
            price_text = convert[0].text
            print(f"当前BTC价格:{price_text}")
        else:
            print("未找到价格元素")
        
        time.sleep(5)  # 每5秒更新一次

if __name__ == "__main__":
    t1 = Thread(target=runA)
    t1.daemon = True  # 正确设置守护线程
    t1.start()
    
    # 主线程保持运行,捕获Ctrl+C信号来关闭浏览器
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        driver.quit()

额外优化建议

  • 可以用Selenium的显式等待替换time.sleep(),等目标元素加载完成后再获取,比固定休眠更可靠,避免网络延迟导致的元素找不到问题。
  • 爬页面不如直接用Binance官方API(REST或WebSocket),调用API获取价格更稳定高效,还不会因为页面结构变动导致代码失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:33:47