python - 如何仅将股票名称和实时价格导出到 .txt 文件中,而中间没有任何额外的行或不需要的数据?
问题描述
我正在使用 BeautifulSoup 从网站上抓取实时股票价格,并使用 Python 将其导出到文本文件中。该代码返回价格以及其他行和信息。
如何仅选择要导出到 .txt 文件的特定信息?
我还不太熟悉python。尝试搜索stackoverflow,但找不到任何对我有用的东西。
from bs4 import BeautifulSoup
import requests
import time
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)
file = open("test.txt", "a")
file.write(str(cols))
file.write("\n")
file.close()
time.sleep(10) # this will wait for 10 seconds
当前代码导出数据如下:
[]
['S&P 500 FUTURES', '2,948.50', '+29.50', '+1.01%', '2,953.62', '2,882.12']
['Open Last Trade : 16:38', 'US Time : Thu Oct 10 2019 16:38']
[]
['S&P 500 FUTURES', '2,948.50', '+29.50', '+1.01%', '2,953.62', '2,882.12']
['Open Last Trade : 16:38', 'US Time : Thu Oct 10 2019 16:38']
[]
我需要的是(中间没有任何空白行):
'S&P 500 FUTURES', '2,948.50'
'S&P 500 FUTURES', '2,949.80'
解决方案
使用,if
要检查的语句cols
不为空,并且str
' 加入从列表中创建一个逗号分隔的字符串,cols
如下所示:
from bs4 import BeautifulSoup
import requests
import time
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]
if cols:
result = ", ".join(cols)
print(result)
with open("test.txt", "a") as f:
f.write(result)
f.write("\n")
time.sleep(10) # this will wait for 10 seconds
注意:我还使用了一个关键字with
,它基本上负责文件对象的自动打开和关闭。
在此处阅读有关它的更多信息
推荐阅读
- autodesk-forge - Autodesk - Forge Viewer - 标记 - 在加载标记时无法在标记扩展中获取标记数组
- node.js - multer文件上传不显示文件存储的路径
- visual-studio-2019 - VS2019 测试资源管理器未使用 specflow+runner 为 netcoreapp3.1 项目运行测试
- typescript - 为什么 TypeScript 3.7.5 在键入接收数组的函数时会抛出错误?
- asp.net-core - 如何使用 ChallengeAsync 重定向到 asp.net 核心中的中间件内的登录页面
- kubernetes - Kubernetes 副本集和数据库
- python - 在 Python 中传递要作为参数执行的函数
- loops - 如何捕获可变文件内容?
- oauth-2.0 - 在 Outlook 插件中实施 oAuth2 身份验证
- javascript - 使用 JQuery 从轮播中删除按钮单击时的照片