我正在尝试记录网站上的covid数据,并每天更新新的案例。到目前为止,我已经成功地通过抓取将病例数量放入了文件中,但每天我都必须手动输入日期并运行文件以获取更新的统计数据。我该如何编写一个脚本来每天更新CSV,使用新的日期和新的案例数量,同时保存旧的以供将来使用?
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()发布于 2020-05-13 10:57:39
如果您想保留csv文件的较旧内容,请在追加模式下打开该文件(正如@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脚本。
您可以查看here以了解详细信息。
如果你使用的是Windows,你可以看看this的问题。
https://stackoverflow.com/questions/61764164
复制相似问题