首页 > 解决方案 > f.write('string') 在 python 中只写一次 while true 循环

问题描述

好的,所以我试图制作一个脚本,每 3 秒左右抓取一次比特币的当前价格,打印该数字,然后将其写入文本文件以供以后使用,但是当我运行下面的代码时,它只写我第一次运行代码时将变量放入文本文件

from bs4 import BeautifulSoup
import requests
import time

source = requests.get('https://cryptowat.ch/').text

soup = BeautifulSoup(source, 'lxml')

f= open("bitcoinPrice.txt","w+")

while True:
    source = requests.get('https://cryptowat.ch/').text
    soup = BeautifulSoup(source, 'lxml')
    article = soup.find('span', class_='price').prettify()
    split = article.split()
    cost = split[2]
    price = cost + ' USD'
    f.write(price)
    print(price)
    time.sleep(1)

标签: pythonweb-scraping

解决方案


如果你想将所有价格逐行写入文件,也可以写一个换行符:

while True:
    source = requests.get('https://cryptowat.ch/').text
    soup = BeautifulSoup(source, 'lxml')
    article = soup.find('span', class_='price').prettify()
    split = article.split()
    cost = split[2]
    price = cost + ' USD'
    f.write(price)
    f.write('\n')
    print(price)
    time.sleep(1)

此外,由于文件未关闭,请使用上下文管理器:

with open("bitcoinPrice.txt","w+") as f:
    while True:
        source = requests.get('https://cryptowat.ch/').text
        soup = BeautifulSoup(source, 'lxml')
        article = soup.find('span', class_='price').prettify()
        split = article.split()
        cost = split[2]
        price = cost + ' USD'
        f.write(price)
        print(price)
        time.sleep(1)

推荐阅读