有一天在逛知乎可以用 Python 编程语言做哪些神奇好玩的事情?发现一条有趣的评论,说是通过python实现每日向女票(当然你也可以发给你的基友)发送一封爱意满满的邮件,当时觉得挺有趣的,于是就照模照样的也用python实现一次。整个代码的思路也很简单。爬取数据、云储存获取数据——整理排版——邮件发送。
先放张效果图:
本次实例用到的框架有:leancloud、requests、lxml、smtplib、email。
1、首先爬取情话和带有我爱你文字的电影截图储存在leancloud数据库中。leancloud的使用可以参照它们的开发文档。
2、爬取天气信息。
天气信息我看了很多网站,最后选择爬取墨迹天气的信息。一是墨迹天气存在的时间比较久了,信息准确充足,更新也及时。二是墨迹天气上关于天气的生活服务信息也足够多。
response = requests.get(url, headers=headers) if not response.status_code == 200: print('天气详情请求错误:' + str(response.status_code)) return # 对获取到的req格式化操作,方便后面用xpath解析 sel = html.fromstring(response.text) # 查询城市 location = sel.xpath('//div[@class="search_default"]/em/text()')[0] # 今日天气提醒 tip = sel.xpath('//div[@class="wea_tips clearfix"]/em/text()')[0] # 天气情况 # weathers = sel.xpath('//div[@class="forecast clearfix"]/ul[@class="days clearfix"]/li/text()')[0].extract() # 空气质量 air = '空气质量' + sel.xpath('//div[@class="wea_alert clearfix"]/ul/li/a/em/text()')[0] # 天气类型 weather_type = sel.xpath('//div[@class="wea_weather clearfix"]/em/text()')[0] + '°C' # 温度范围 temperature_range = sel.xpath('//div[@class="wea_weather clearfix"]/b/text()')[0] # 湿度 humidity = sel.xpath('//div[@class="wea_about clearfix"]/span/text()')[0] # 风向 wind_direction = sel.xpath('//div[@class="wea_about clearfix"]/em/text()')[0] # 控油化妆、感冒、穿衣、空气、运动、紫外线 sites = ['https://tianqi.moji.com/makeup/china/guangxi/%s' % city, 'https://tianqi.moji.com/cold/china/guangxi/%s' % city, 'https://tianqi.moji.com/dress/china/guangxi/%s' % city, 'https://tianqi.moji.com/pollution/china/guangxi/%s' % city, 'https://tianqi.moji.com/sport/china/guangxi/%s' % city, 'https://tianqi.moji.com/uray/china/guangxi/%s' % city] weather_info = [] for site in sites: response = requests.get(site, headers=headers) if not response.status_code == 200: continue sel = html.fromstring(response.text) type = sel.xpath('//div[@class="aqi_info_detail"]/span/text()')[0] level = sel.xpath('//div[@class="aqi_info_detail"]/em/text()')[0] desc = sel.xpath('//dl[@class="aqi_info_tips"]/dd/text()')[0] weather_info.append(type + '指数:' + level + '-' + desc)
3、爬取星座运势信息
# 星座运势 response = requests.get('https://www.xzw.com/fortune/virgo/') if not response.status_code == 200: print('星座运势请求错误:' + str(response.status_code)) return sel = html.fromstring(response.text) fortune = sel.xpath('//div[@class="c_box"]/div[@class="c_cont"]/p/span/text()')[0]
4、组合获取数据
# 计算相恋天数 inLoveDate = datetime.datetime(****, **, **) todayDate = datetime.datetime.today() inLoveDays = (todayDate - inLoveDate).days print('你们相恋了' + str(inLoveDays) + '天') # 初始化leancloud对象 LoveWords = leancloud.Object.extend('LoveWords') LovePhoto = leancloud.Object.extend('LovePhoto') # 计算发送天数 beginSendDate = datetime.datetime(2017, 12, 15) todaySendDate = datetime.datetime.today() sendDays = (todaySendDate - beginSendDate).days + 1 # 查询情话 query = LoveWords.query query.equal_to('id', sendDays) loveWord = query.first().get('loveWord') # 查询图片 query = LovePhoto.query query.equal_to('id', sendDays) lovePhotoSrc = query.first().get('lovePhotoSrc') weather_detail = weather_type + temperature_range + '|' + air + '|' + humidity + '|' + wind_direction
5、发送邮件
如果对python发送邮件这块不太熟悉的朋友可以查看这篇文章SMTP发送邮件
# 发送方邮件地址 from_addr = ('*********.com') # 授权码 password = ('********') # 接收方邮件地址 to_addr = ('*********.com') # smtp服务 smtp_server = ('smtp.126.com') # 邮件对象: msg = MIMEMultipart() msg['From'] = _format_addr(u'***********<%s>' % from_addr) msg['To'] = _format_addr(u'************<%s>' % to_addr) msg['Subject'] = Header(u'************', 'utf-8').encode() # 构建邮件文本对象 msg_text = MIMEText('html编写的发送内容','html', 'utf-8') # 构建邮件图片对象 # 设置附件的MIME和文件名,这里是jpg类型: mime = MIMEBase('image', 'jpg', filename='love.jpg') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='love.jpg') mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: req = requests.get(lovePhotoSrc) mime.set_payload(req.content) # 用Base64编码: encoders.encode_base64(mime) # 将邮件文本对象和邮件图片对象添加到邮件对象 msg.attach(msg_text) msg.attach(mime) server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit()
总结:
到此,整个项目就编写完成了,只需要定一个定时任务每天执行这个python程序就可以每天自动发送一封这样的邮件了,怎么样,是不是很浪漫~,如果你有女朋友或者女神赶紧写个程序给他发邮件吧!