首页 > 解决方案 > 如何在 python 中每 2 分钟重置并重新运行此代码?while 循环对我来说失败了

问题描述

我需要帮助才能运行此代码并每 2 分钟获取一次更新价格。

我尝试了 while 循环,但它在第一次抓取后停止抛出值。仅刷新结果中的日期和时间,而不是价格。

from bs4 import BeautifulSoup
import requests


result = requests.get("https://liveindex.org/s&p-futures/")
src = result.content
soup = BeautifulSoup(src, 'lxml')
table_body=soup.find('tbody')
rows = table_body.find_all('tr')

for row in rows:
    cols=row.find_all('td')
    cols=[x.text.strip() for x in cols]
    print(cols)

我需要创建一个实时代码来获取最新的股票价格。该代码可以刮掉价格,但只能刮一次。手动重启有效,但这不是我想要的。

标签: pythonpython-3.xbeautifulsoup

解决方案


您可以每隔一分钟尝试一次:

from bs4 import BeautifulSoup
import requests
import time # you need this module

# this will run forever
while True:
    result = requests.get("https://liveindex.org/s&p-futures/")
    src = result.content
    soup = BeautifulSoup(src, 'lxml')
    table_body=soup.find('tbody')
    rows = table_body.find_all('tr')

    for row in rows:
        cols=row.find_all('td')
        cols=[x.text.strip() for x in cols]
        print(cols)

    time.sleep(120) # this will wait for 120 seconds

推荐阅读