【问题标题】:I can't write data into csv by schedule我无法按计划将数据写入 csv
【发布时间】:2023-07-10 09:24:01
【问题描述】:

我将计划设置为 30 秒,但数据将每 1-2 秒写入 csv ...... 我尝试了很多方法来修复它,但没有任何用处。 希望我每 30 秒将数据写入 csv 中。 希望有人能帮我解决一下,非常感谢!

import bs4
import requests
import schedule
import time
import smtplib
import email.message
from win10toast import ToastNotifier
from function import send_email
from datetime import datetime as dt
import csv


stock_no = input('Please insert stock no:')
set_price = '%.2f' % float(input('Please set notification price:'))


def get_stock_price():
    links = 'https://histock.tw/stock/%s' % stock_no
    response = requests.get(links)
    soup = bs4.BeautifulSoup(response.text, 'lxml')
    tittle = soup.find('h3').get_text().strip()
    li = soup.find('span', id="Price1_lbTPrice").span.get_text()
    time_now = dt.utcnow().strftime('%Y-%m-%d %H:%M:%S')

    with open('C:/Python workspace/stock_value_notification/index.csv', 'a', newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([tittle, li, time_now])

    return li, tittle, time_now


schedule.every(10).seconds.do(get_stock_price)

while True:
    try:
        schedule.run_pending()
        time.sleep(1)
        current_price = get_stock_price()[0]

        if set_price == current_price:
            msg_text = get_stock_price()[1] + \
                'stock value is  ' + current_price
            send_email(msg_text)
            toaster = ToastNotifier()
            toaster.show_toast("Stock value notification",
                               msg_text,
                               duration=10)
    except:
        print('It is not working...')
        break

this csv file is the result I program

【问题讨论】:

    标签: python csv file schedule


    【解决方案1】:

    您以错误的方式使用时间表。 我希望这个伪代码示例对您有所帮助:

    def scrape_and_save():
        res = scrape()
        save_to_csv(res)
    
    schedule.every(10).seconds.do(scrape_and_save)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

    • 哦!我知道了!!非常感谢
    【解决方案2】:

    您必须将通知部分移至单独的函数或get_stock_price()。这是一个有效的重构代码。

    Schedule 将在每个时间间隔调用get_stock_price,一旦数据写入 o/p 文件,稍后就会调用通知。

    根据您的需要进一步调整它。

    import bs4
    import requests
    import schedule
    import time
    from win10toast import ToastNotifier
    from datetime import datetime as dt
    import csv
    import sys
    
    stock_no = input('Please insert stock no:')
    set_price = '%.2f' % float(input('Please set notification price:'))
    
    
    def get_stock_price():
        try:
            links = 'https://histock.tw/stock/%s' % stock_no
            response = requests.get(links)
            soup = bs4.BeautifulSoup(response.text, 'lxml')
            tittle = soup.find('h3').get_text().strip()
            li = soup.find('span', id="Price1_lbTPrice").span.get_text()
            time_now = dt.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        
            with open('index.csv', 'a', newline='', encoding="utf-8") as csv_file:
                writer = csv.writer(csv_file)
                writer.writerow([tittle, li, time_now])
        
            notify(li, tittle)
    
        except Exception as e:
            print('It is not working...')
            print(e)
            sys.exit()
    
    
    def notify(current_price, stock_title):
    
        if set_price == current_price:
            msg_text = stock_title + \
                       ' stock value is  ' + current_price
            toaster = ToastNotifier()
            toaster.show_toast("Stock value notification",
                               msg_text,
                               duration=10)
    
    schedule.every(10).seconds.do(get_stock_price)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    PS:网络抓取活动可能会导致额外的延迟,有时会增加执行时间。

    【讨论】:

    • 感谢您解决了这个问题!!它给了我很多帮助。