自我更新应用程序无法有效运行

时间:2015-12-02 19:42:09

标签: python while-loop web-scraping beautifulsoup sleep

我制作了一个从网页上抓取数据并获取当前比特币价格(以及索引)并将其显示在标签上的程序。为了更新自己的价格,我把代码放在一个无限的while循环中,这样它就会不断更新自己。我遇到的问题是它似乎使用了很多cpu。我尝试在while循环中使用time.sleep,但这使得程序响应性降低,而且更加迟钝。这是代码:

def bitcoinPrice():
    url = 'http://www.coindesk.com/price/'
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    btcPrice = soup.find('div', attrs=
    {'class' : 'bpi-value bpiUSD'}
                 )
    btcIndex = soup.find('span', attrs=
    {'class' : 'bpi-change changeUSD data-down'}
                     )
    return btcPrice.text + "(" + btcIndex.text + ")"



def bitcoinLabel():
    theLabel = Label(root, text = bitcoinPrice())
    theLabel.pack()
    while True:
        sleep(1)
        theLabel.configure(text = bitcoinPrice())
        root.update()


bitcoinLabel()

编辑:我还注意到,每当价格发生变化时,它会在显示新值之前在旧值和新值之间轻弹几秒钟,然后停止"轻弹"。不知道为什么会发生这种情况(不是一个大问题,只是想指出这一点)。

0 个答案:

没有答案