#由于每天早上要和妹子说早安,于是做个定时任务,每天早上自动爬取天气,发送天气问好邮件
#
#涉及模块:
#(1)定时任务:windows的定时任务
# 配置教程链接:http://blog.csdn.net/wwy11/article/details/51100432
#(2)爬取天气:用的是中国天气网 http://www.weather.com.cn/weather/101190101.shtml 101190101为城市id,动态获取
# 爬虫代码见上一篇博客 http://www.cnblogs.com/chenyuebai/p/6728532.html
#(3)发送邮件:代码同在上一篇博客
#(4)结束处理:笔记本自动关机,代码同在上一篇博客 #os.system('shutdown -s -t 1')
#20170427 加入失败重试;优化邮件正文
#################################################################
#author: 陈月白
#_blogs: http://www.cnblogs.com/chenyuebai/
################################################################# # -*- coding: utf-8 -*-
import sys
import time
import os
import traceback
import crawler_tools_01 # curPath = os.path.abspath(os.path.dirname(__file__))
# sys.path.append(curPath) city_code_dic = {
"南京": "",
"北京": ""
} class MORNING(crawler_tools_01.CRAWLER):
#获取城市id,返回url
def get_wertherUrl_by_cityName(self, cityName):
cityId = city_code_dic[cityName]
if cityId == "":
print("get cityId failed,use default:101010100 " % cityName)
wertherUrl = "http://www.weather.com.cn/weather/" + "" + ".shtml"
return wertherUrl
else:
wertherUrl = "http://www.weather.com.cn/weather/" + cityId + ".shtml"
# print(wertherUrl)
return wertherUrl #获取天气信息
def get_today_weather_by_weatherUrl(self,weatherUrl):
flag_today = '<li class="sky skyid lv2 on">.*?<h1>(.*?)</h1>.*?</big>.*?title=(.*?)class.*?<span>(.*?)</span>.*?<i>(.*?)</i>.*?span title=(.*?)class=.*?<i>(.*?)</i>'
items_today_tmp = self.select_items_from_url(weatherUrl,flag_today) #获取页面信息失败重试一次
if not items_today_tmp:
items_today_tmp = self.select_items_from_url(weatherUrl,flag_today)
print("items_today_tmp =",items_today_tmp) #数据处理 元组转列表
items_today = []
try:
for i in items_today_tmp[0]:
items_today.append(i)
print("items_today =", items_today)
return items_today
except:
traceback.print_exc()
print("CATCH AN ERROR AT:items_today_tmp transTo items_today")
return items_today_tmp def make_mail_body(self,items_today):
try:
body_text = "美好的一天,从我的问候开始~~~\n \n今日天气:\n%s: %s 温度:%s 至 %s %s %s\n \n \n请根据温度注意穿衣,阴雨天记得带伞 \n from Mr.ch"%(items_today[0], items_today[1], items_today[2], items_today[3], items_today[4], items_today[5])
return body_text
except:
traceback.print_exc()
body_text = "美好的一天,从我的问候开始~~~\n \n今日天气:%s\n \n \n请根据温度注意穿衣,阴雨天记得带伞 \n \n from Mr.ch" % items_today
return body_text def main():
ZMJ = MORNING()
weatherUrl = ZMJ.get_wertherUrl_by_cityName("南京")
print("01 weatherUrl =", weatherUrl)
# 获取今日天气信息
items_today = ZMJ.get_today_weather_by_weatherUrl(weatherUrl)
#生成邮件正文
body_text = ZMJ.make_mail_body(items_today) #发送邮件
date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
#ZMJ.send_email(["50*******@qq.com"], "爱心天气预报_%s"%date,body_text) ZMJ.send_email(["50*******@qq.com","46********@qq.com"], "爱心天气预报_%s"%date,body_text)
ZMJ.shutdown(10) main()
运行结果: