繁体   English   中英

如何每天更新和保存数据到 CSV 文件?

[英]How do I update and save data to a CSV file each day?

我正在尝试从网站记录 covid 数据,并每天使用新病例对其进行更新。 到目前为止,我已经设法通过抓取将病例数放入文件中,但每天我都必须手动输入日期并运行文件以获取更新的统计数据。 我将如何 go 编写一个脚本,该脚本将每天更新 CSV,包含新的日期和新的案例数量,同时保存旧的以供将来使用? 我写了这个并在 Virtual Studio Code 中运行它。

import csv
import bs4
import urllib
from urllib.request import  urlopen as uReq
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup

#For sites that can't be opened due to Urllib blocker, use a Mozilla User agent to get access
pageRequest = Request('https://coronavirusbellcurve.com/', headers = {'User-Agent': 'Mozilla/5.0'})
htmlPage = urlopen(pageRequest).read()
page_soup = soup(htmlPage, 'html.parser')
specificDiv = page_soup.find("div", {"class": "table-responsive-xl"})

TbodyStats = specificDiv.table.tbody.tr.contents
TbodyDates = specificDiv.table.thead.tr.contents

def writeCSV():
    with open('CovidHTML.csv','w', newline= '') as file:
        theWriter = csv.writer(file)  

        theWriter.writerow(['5/8', ' 5/9', ' 5/10',' 5/11',' 5/12'])
        row = []
        for i in range(3,len(TbodyStats),2):
            row.append([TbodyStats[i].text])

        theWriter.writerow(row)


 writeCSV()

如果要保留 csv 文件的旧内容,请在 append 模式下打开文件(正如@bfris 正确指出的那样)

    with open('CovidHTML.csv','a', newline= '') as file:

如果您使用的是 Linux,您可以设置一个cron作业以每天在某个特定时间调用 python 脚本。 首先,使用which命令定位到 python 的路径:

$ which python3 

这给了我

/usr/bin/python3

然后 cron 作业将如下所示:

10 14 * * * /usr/bin/python3 /path/to/python/file.py

将此行添加到 crontab 文件中。 这将在每天下午 2:10 调用 python 脚本。
您可以在这里查看详细信息。

如果您使用的是 Windows,您可以看看这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM