python爬虫(2)--定时任务
应用场景
老板:每隔一段时间收集一下商品的浏览量
我:
一顿操作猛如虎,终于给搞定了
#设置文档标题
with open('my_content.csv', 'a+', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
#文档列表头
writer.writerow(['deal_title','dealScore', 'views', 'comments', 'time'])
print("任务马上开始,请耐心等待5秒钟!")
#任务标识
flag = 0
#记录任务数
count = 0
# 获取当前时间
now = datetime.datetime.now()
#启动时间,为当前时间加5秒
sched_timer = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute+now.second) + datetime.timedelta(seconds=5)
while(True):
# 当前时间
now = datetime.datetime.now()
if sched_timer < now < sched_timer + datetime.timedelta(seconds=1):
time.sleep(1)
print(now)
# 运行抓取网页程序
main(sched_timer)
# 将标签设为 1
flag = 1
count +=1
print("完成第"+str(count)+"次!")
else:
# 标签控制 表示主程序已运行,才修改定时任务时间
if flag == 1:
# 修改定时任务时间 时间间隔为2分钟
sched_timer = sched_timer + datetime.timedelta(minutes=2)
flag = 0
结果: