ubuntu 定时发送当天天气邮件提醒上班的自己
爬取当前时间天气,发送邮件脚本分享
#页面请求
import os
import re
import requests
#数据提取
from bs4 import BeautifulSoup
from lxml import etree
#数据存储
import csv
#打开文件,避免空行
import codecs
#设置爬取的随机延迟
import time
import random
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import time
import os
def get_ua():
headers = {
‘User-Agent’: ‘Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)’
}
return headers
def get_tianqi(url):
response = requests.get(url, headers=get_ua())
# response = down(url=url)
html = response.text
# print(html)
# 提取数据
html = etree.HTML(html)
#print(html)
print(“+++”)
# 分析结果,编写 xpath 匹配表达式
# //ul[@class=‘mi_ul’]/span/a
# ls = html.xpath(‘//img[contains(@class ,“alignnone size-full loading”)]’)
real_t = html.xpath(‘//span[@class=“real-t”]/text()’)[0].strip()
real_today = html.xpath(‘//div[@class=“real-today”]/span/text()’)[0].strip()
# print(real_t)
print(real_today)
return real_today
def send_email():
mail_host=“smtp.qq.com”
mail_user=“154654@qq.com”
mail_pass=“####”
sslPort=“465”
time1=time.strftime(‘%Y-%m-%d %H:%M:%S’,time.localtime(time.time()))
sender = ‘1987617587@qq.com’
to_reciver = [‘6496@qq.com’]
cc_reciver =[‘16564@163.com’]
reciver = to_reciver + cc_reciver
message = MIMEMultipart()
# message = MIMEText(‘dddddddddd’, _subtype=‘html’, _charset=‘utf-8’)
message[“subject”] = time1 + “天气情况汇报” # 邮件的标题
# 邮件正文
mail_context = get_tianqi(‘http://tianqi.2345.com/luoyang1d/57073.htm’)
message.attach(MIMEText(mail_context, ‘plain’, ‘utf-8’))
message[‘From’] = sender
message[‘To’] = “;”.join(to_reciver)
message[‘Cc’] = “;”.join(cc_reciver)
try:
smtpObj = smtplib.SMTP_SSL(mail_host,sslPort)
smtpObj.ehlo()
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,reciver, message.as_string())
print (“邮件发送成功”)
except Exception as n:
print (“Error: 无法发送邮件”)
print(n)
send_email()
crontab -e
编辑 ubuntu 下 cron 指令,每天 7 点发送邮件
0 7 * * * /home/ubuntu/.virtualenvs/venv1/bin/python /home/ubuntu/jupyter_notebook/1.py >> /home/ubuntu/jupyter_notebook/1.txt
service cron restart
重启定时任务
没必要,一天就两句话,维护的时候,可以删除的,自己的日志留着没什么用
那你这个会不会把所有日志都写到这个里面了,你可以让它每天的日志写到每天的 txt 文件里,按日期命名
👍 👍
是的啊
最后这个“>> /home/ubuntu/jupyter_notebook/1.txt” 是想把日志输出到这里吗