python - 如何在 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)
我需要创建一个实时代码来获取最新的股票价格。该代码可以刮掉价格,但只能刮一次。手动重启有效,但这不是我想要的。
解决方案
您可以每隔一分钟尝试一次:
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
推荐阅读
- python - Docker gremlin-server:“无法分配请求的地址”
- python - 如何在 Python 中跨不同线程修改变量?
- sdl-2 - 在 c 中显示纹理的 SDL2 问题
- mapbox-gl-js - 当我在 mapbox gl js 中单击地图上的多边形时,是否必须使用 geojson 文件来获取数据?
- java - Hazelcast - 检测虚假共享
- intellij-idea - IntelliJ IDE 始终以演示模式启动
- swift4.2 - UI 未使用子视图控制器更新
- python - 我的批处理文件无法识别 pygame
- html - 更改 CSS 元素的位置(从左到右的装饰花括号)
- reactjs - Nginx + 带有路由器的 React 应用程序 + Chrome = 子文件夹不起作用