想知道是否有更好的更新文件的方法?

Wondering if there is a better way to update files?

我目前有一个 python 程序,它既是网络抓取程序,也是文件编写器,它使用 windows 10 任务计划程序更新我桌面上的数据库。问题是,由于某种原因,任务计划程序不会在指定时间 100% 的时间 运行 python 文件。我想知道是否有更好的方法来确保文件在指定时间更新,只要计算机处于开启状态。

我试过更改任务计划程序设置,但我仍然遇到这个问题。

import requests
from bs4 import BeautifulSoup
from datetime import datetime
#Updates Everyday.
#Fantasy5-WebScraper
response = requests.get('https://www.lotteryusa.com/michigan/fantasy-5/')
soup = BeautifulSoup(response.text, 'html.parser')
date = soup.find(class_='date')
results = soup.find(class_='draw-result list-unstyled list-inline')
d = datetime.strptime(date.time['datetime'], '%Y-%m-%d')
Fantasy5 = (d.strftime("%Y-%m-%d")+(',')+results.get_text().strip().replace('\n',','))
print(Fantasy5)

#Writing to DataBase
with open("Filename.txt", "r") as f:
data = f.read()

with open("Filename.txt", "w") as f:
    f.write('{}{}{}'.format(Fantasy5, '\n' if data else '', data))
    f.close()

#Writing to DataFrame
with open("Filename.txt", "r") as f:
    data = f.read()

with open("Filename.txt", "w") as f:
    f.write('{}{}{}'.format(Fantasy5, '\n' if data else '', data))
    f.close()

您可以使用日程安排来完成这项任务。然后将 python 文件添加到启动中,这样它就会在每次启动计算机时执行。

此程序将在每天早上 6 点执行作业。

import schedule
import time
import requests
from bs4 import BeautifulSoup
from datetime import datetime

def job(t):
    response = requests.get('https://www.lotteryusa.com/michigan/fantasy-5/')
    soup = BeautifulSoup(response.text, 'html.parser')
    date = soup.find(class_='date')
    results = soup.find(class_='draw-result list-unstyled list-inline')
    d = datetime.strptime(date.time['datetime'], '%Y-%m-%d')
    Fantasy5 = (d.strftime("%Y-%m-%d")+(',')+results.get_text().strip().replace('\n',','))
    print(Fantasy5)

    #Writing to DataBase
    with open("Filename.txt", "r") as f:
        data = f.read()

    with open("Filename.txt", "w") as f:
        f.write('{}{}{}'.format(Fantasy5, '\n' if data else '', data))
        f.close()

    #Writing to DataFrame
    with open("Filename.txt", "r") as f:
        data = f.read()

    with open("Filename.txt", "w") as f:
        f.write('{}{}{}'.format(Fantasy5, '\n' if data else '', data))
        f.close()
    return

schedule.every().day.at("06:00").do(job,'It is 06:00')

while True:
    schedule.run_pending()
    time.sleep(60)