如何每 10 分钟将数据从 Web 写入 CSV 文件



你好,我对Python和网络抓取相当陌生,但我正在尝试从网站获取数据值,并将其写入CSV文件。这对我来说也很好。我的问题是我希望脚本每小时获取一次值并将其存储在 CSV 文件中。所以我对调度命令做错了,因为获取值并将其写入 CSV 文件效果很好,但只有在我按运行时。这是我尝试过的代码。

import urllib2
from bs4 import BeautifulSoup
import csv
from datetime import datetime
import os
import schedule
import time

def job():
url = 'https://coinmarketcap.com/currencies/bitcoin-cash/'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
name_box = soup.find('span', attrs={'class': 'text-large2'})
bch_value = float(name_box.text.strip())
os.chdir('C:UsersNIK.spyder2PythonScripts')
with open('BCH_kurs', 'a') as csv_file:
writer = csv.writer(csv_file)
writer.writerow([bch_value, datetime.now()])
schedule.every(1).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
while True:
schedule.run_pending()
time.sleep(1)

时间表是一个

定期作业的进程内调度程序 ( https://pypi.python.org/pypi/schedule (

因此,计划在一个进程中运行。 要启动此过程,您必须使用"运行"并在该"计划运行">中启动该过程...

我建议你探索scrapy框架。这是一个简单的例子

您可以保存为所需的任何格式,还可以以固定的间隔自动运行抓取。

最新更新