036-使用crontab定时爬虫

 

 

不得不说

这次弄crontab花了很长时间

本来这种东西我是肯定会写一篇博客的

但是不知道为什么最近真的太懒了

连这么重要的知识点也不写博客

真的是服了

现在开始吧

 

 

先是看一下爬虫代码

比如我们现在要获取

https://www.d1xz.net/yunshi/today/Aries/

这个网站的信息

 

那么现在我们来写一个get请求来获取信息

import urllib.request
import re
import sqlite3
from lxml import html

url = 'https://www.d1xz.net/yunshi/today/Aries/'

# 请求得到response
response = urllib.request.urlopen(url)
decode = response.read().decode()

# 用etree来解析
etree = html.etree
etree_html = etree.HTML(decode)

# 从html中取出元素class
xpath = etree_html.xpath('//*[@class="det"] ')
# xpath = etree_html.xpath('//*[@class="det week_det"] ')

result = etree.tostring(xpath[0], encoding='utf-8').decode('utf-8')
print(result)

 

 

现在我们已经获取到信息了

那么我们要把信息存到数据库里面

# 把记录添加到数据库
db = sqlite3.connect('../db.sqlite3')
cursor = db.cursor()
cursor.execute(sql_insert)
db.commit()
cursor.close()

现在数据库在我们的py文件的上一层,

 

 

 

现在我们弄一下crontab

假设现在有几种不同的情况

那么我们要来设置crontab执行时间

 

每个小时
0 * * * * cd /root/TestProject/crontab; python3 crontab_test.py;
每3个小时
0 */3 * * * cd /root/TestProject/crontab; python3 crontab_test.py;
每12个小时
0 */12 * * * cd /root/TestProject/crontab; python3 crontab_test.py;
每天9点
0 9 * * * cd /root/TestProject/crontab; python3 crontab_test.py;
每天10点
0 10 * * * cd /root/TestProject/crontab; python3 crontab_test.py;

 

我们要

1.设置时间

2.cd 进入目录,因为本来的执行目录在root

3.然后再python3执行

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值