首页 > 解决方案 > 如何仅将股票名称和实时价格导出到 .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'

标签: pythonbeautifulsoup

解决方案


使用,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,它基本上负责文件对象的自动打开和关闭。

在此处阅读有关它的更多信息


推荐阅读