情侣之间除了平日一起探究有趣的事情,总是少不了就是 “日常早晚请安”
1、请安情景一
男: 今日阳光明媚,多云转晴,小懒猪快起床啦
女:早起啦,话说你是不是还在被窝里呢
男:嘿嘿
2、请安情景二
女:哎呀,挺晚了呢,早点休息吧,晚安
男:晚安
女:么么哒
一分钟后。。。
女:快说,你是不是还在扣手机呢
男:嘿嘿
另外你的小可爱有没有要求你每晚给她讲故事,无奈故事库那是相当匮乏!那可不可以让聊天更智能一些呢!于是懒惰的程序员学会了爬虫,嗯就是在网页上会爬的虫,下面介绍通过爬虫~实现定时的早晚安,告别手动,人工智能!
一、早安,天气预报
使用python的第三方模块itchat实现早安问候,itchat是个基于网页版微信的python微信API。功能目前做到基本可以满足正常的消息收发,信息的获取等等。itchat的详细介绍和使用可参加官网:itchat
话不多说直接给出程序源码,下面天气是从中国天气官网上获取的北京市海淀区的天气,如果是其他地区可更换网址,:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import itchat as ic
import time
import re
def getWeather():
# 使用BeautifulSoup获取天气信息
resp=urlopen('http://www.weather.com.cn/weather/101010200.shtml')
soup=BeautifulSoup(resp,'html.parser')
tagDate=soup.find('ul', class_="t clearfix")
dates=tagDate.h1.string
tagToday=soup.find('p', class_="tem")
try:
temperatureHigh=tagToday.span.string
except AttributeError as e:
temperatureHigh=tagToday.find_next('p', class_="tem").span.string
temperatureLow=tagToday.i.string
weather=soup.find('p', class_="wea").string
tagWind=soup.find('p',class_="win")
winL=tagWind.i.string
content = '早上好,小宝!\n 今日分海淀区天气请注意查收:\n' + '今天是:' + dates + '\n' + '风级:' + winL + '\n' + '最低温度:' + temperatureLow + '\n' + \
'最高温度:' + temperatureHigh + '\n' + '天气:' + weather + '\n'
return content
def main():
try:
message = getWeather()
print('成功获取天气信息')
except:
message = ""
print("获取天气信息失败")
# 参数hotReload=True实现保持微信网页版登陆状态,下次发送无需再次扫码
ic.auto_login(hotReload=True)
users = ic.search_friends(name = '手动打码')
userName = users[0]['UserName']
ret = ic.send(msg = message, toUserName = userName)
if ret:
print("成功发送")
else:
print("发送失败")
time.sleep(60)
ic.logout()
if __name__ == '__main__':
main()
二、午安,每日一练
每天督促女友和自己学习也是十分重要的,下面便是通过python的wxpy模块实现给女友定时发送金山词霸每日一练的原文和翻译,wxpy模块的详细介绍和使用可参见官网:wxpy,代码呈上:
from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests
import random
# 设置cache_path=True, 保持微信登陆状态
bot = Bot(cache_path=True)
# linux执行登陆请调用下面的这句
# bot = Bot(console_qr=2,cache_path="botoo.pkl")
def get_news():
# 获取金山词霸的每日一句的英文和翻译
url = "http://open.iciba.com/dsapi/"
r = requests.get(url)
content = r.json()['content']
note = r.json()['note']
return content, note
def main():
try:
contents = get_news()
# 你朋友的微信名称,不是备注,也不是微信帐号
my_friend = bot.friends().search('手动打码')[0]
my_friend.send(contents[0])
my_friend.send(contents[1])
my_friend.send(u"小宝,每日一练开始了!")
# 每86400秒(1天),发送1次
t = Timer(86400, send_news)
# 通过生成随机数,使得每次发送的时间不固定
ran_int = random.randint(0,100)
t = Timer(86400+ran_int,send_news)
t.start()
except:
my_friend.send(u"今日消息发送失败了")
if __name__ == "__main__":
main()
三、晚安,睡前讲故事
哈哈,睡前小故事不用愁,爬虫让睡前故事无穷无尽!上面两种方式都是微信定时发送,下面给出不同的方式,发送小故事到亲爱的邮箱,每日邮箱踩一踩:
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
import random
import time
def parse_html(url, headers):
try:
r = requests.get(url, headers=headers, timeout=60)
r.raise_for_status()
r.encoding = r.apparent_encoding
html_content = r.text
return html_content
except:
return "爬取失败"
def parse_link(urllist, html):
url_baisc = 'http://www.tom61.com/'
soup = BeautifulSoup(html, 'html.parser')
temp = soup.find('dl', attrs={'class': 'txt_box'})
link_list = temp.find_all('a')
for link in link_list:
urllist.append(url_baisc + link.get('href'))
def sendemail(url, headers):
# 发送方邮箱
msg_from = '手动打码'
# 填入发送方邮箱的授权码,不是密码,如使用网易邮箱,需要到网易邮箱里申请
passwd = '手动打码'
# 接收方邮箱
receivers = ['手动打码']
# 邮件主题
subject = '小宝,今日份的睡前小故事,请查收'
# 下面爬取主页面故事内容
html_content = parse_html(url, headers)
text = []
soup = BeautifulSoup(html_content, 'html.parser')
temp = soup.find('div', class_='t_news_txt')
for one in temp.findAll('p'):
text.append(one.text)
content = "小宝,今晚开始讲故事喽:\n\n" + "\n".join(text)
# 配置发送邮件信息
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = ','.join(receivers)
try:
# 邮件服务器及端口号,不同邮箱会有不同
s = smtplib.SMTP_SSL("smtp.163.com", 465)
s.login(msg_from, passwd)
s.sendmail(msg_from, msg['To'].split(','), msg.as_string())
print("发送成功")
except:
print("发送失败")
finally:
s.quit()
def main():
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
}
# 设定时间,保证明天发送不同的故事
initial_time = time.mktime(time.strptime('2019-03-19', "%Y-%m-%d"))
today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
timeArray = time.strptime(today, "%Y-%m-%d")
now_time = int(time.mktime(timeArray))
html_idx = int((now_time - initial_time) // 86400)
url_list = []
url = 'http://www.tom61.com/s/aiqinggushi/'
html_content = parse_html(url, headers)
parse_link(url_list, html_content)
print("爬取故事链接完成")
if html_idx < len(url_list):
sendemail(url_list[html_idx], headers)
else:
print('该页面故事网址以结束,请更换!')
if __name__ == '__main__':
main()
四、crontab,定时任务
如何让程序定时爬起来呢,可以使用crontab命令,使用crontab可以在指定的时间执行脚本或者一系列Linux命令。例如系统管理员安排一个备份任务使其每天都运行,这样便可以实现每日定时的消息发送了。首先你需要在服务器上安装crontab,cron 是linux的内置服务,但它不自动起来,可以用以下的方法启动、关闭这个服务:
/sbin/service crond start : 启动服务
/sbin/service crond stop : 关闭服务
/sbin/service crond restart : 重启服务
/sbin/service crond reload : 重新载入配置
crontab常用命令有:
crontab –e : 修改 crontab 文件. 如果文件不存在会自动创建。
crontab –l : 显示 crontab 文件。
crontab -r : 删除 crontab 文件。
crontab -ir : 删除 crontab 文件前提醒用户。
crontab文件中命令书写规则,下面给出crontab 文件的书写格式:
{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script}
minute: 区间为 0 – 59
hour: 区间为0 – 23
day-of-month: 区间为0 – 31
month: 区间为1 – 12. 1 是1月. 12是12月.
Day-of-week: 区间为0 – 7. 周日可以是0或7.
Crontab 示例
1. 在 12:01 a.m 运行,即每天凌晨过一分钟。这是一个恰当的进行备份的时间,因为此时系统负载不大。
1 0 * * * /root/bin/backup.sh
2. 每个工作日(Mon – Fri) 11:59 p.m 都进行备份作业。
59 11 * * 1,2,3,4,5 /root/bin/backup.sh
or
59 11 * * 1-5 /root/bin/backup.sh
3. 每5分钟运行一次命令
*/5 * * * * /root/bin/check-status.sh
4. 每个月的第一天 1:10 p.m 运行
10 13 1 * * /root/bin/full-backup.sh
5. 每个工作日 11 p.m 运行。
0 23 * * 1-5 /root/bin/incremental-backup.sh
懒惰的程序员快行动起来吧,附上不知在哪里看到的专属程序员的情诗一首,专心做程序员届的伪文青:
世界上最遥远的距离
不是生与死的距离
是你在if我在else
虽然时常一起出现
但永远不会结伴执行
感谢try-catch
让我有机会成为你的finally
守在这必经的渡口