不得不说
这次弄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执行