|
| 1 | +#-*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# 访问12306网站上某天某条线路上的车次信息 |
| 4 | +# 如果有自己关注的票,就发邮件通知 |
| 5 | +# 该程序只访问一次,实际使用时可通过 crontab 或计划任务定时执行 |
| 6 | +# |
| 7 | +# 欢迎关注 |
| 8 | +# 微信公众号:Crossin的编程教室 |
| 9 | +# 微信号:crossincode |
| 10 | +# 论坛:bbs.crossincode.com |
| 11 | + |
| 12 | +import urllib2 |
| 13 | +import json |
| 14 | +import smtplib |
| 15 | +import time |
| 16 | +import codecs |
| 17 | +from email.mime.text import MIMEText |
| 18 | + |
| 19 | +# 记录日志 |
| 20 | +def log(content): |
| 21 | + t = time.strftime('%Y-%m-%d %H:%M:%S') |
| 22 | + f = codecs.open('watcher.log', 'a', 'utf-8') |
| 23 | + f.write('[%s]%s\n' % (t, content)) |
| 24 | + f.close() |
| 25 | + |
| 26 | +# 发送邮件 |
| 27 | +def send_mail(content): |
| 28 | + to_list=[ '[email protected]'] # 接收通知的邮箱 |
| 29 | + mail_host = 'smtp.163.com' #, 587 #设置服务器 |
| 30 | + mail_user = 'username' #替换为发件邮箱用户名 |
| 31 | + mail_pass = 'password' #替换为发件邮箱口令 |
| 32 | + mail_postfix = '163.com' #发件箱的后缀 |
| 33 | + me = "TicketsWatcher"+"<"+mail_user+"@"+mail_postfix+">" |
| 34 | + msg = MIMEText(content,_subtype='plain',_charset='gb2312') |
| 35 | + msg['Subject'] = 'There are some tickets you need.' |
| 36 | + msg['From'] = me |
| 37 | + msg['To'] = ";".join(to_list) |
| 38 | + server = smtplib.SMTP() |
| 39 | + server.connect(mail_host) |
| 40 | + server.ehlo() |
| 41 | + server.starttls() |
| 42 | + server.login(mail_user,mail_pass) |
| 43 | + server.sendmail(me, to_list, msg.as_string()) |
| 44 | + server.close() |
| 45 | + log('sent mail successfully') |
| 46 | + |
| 47 | + |
| 48 | +try: |
| 49 | + # 请求地址根据实际要抓取的页面修改,参数包括日期、出发站、到达站 |
| 50 | + resp = urllib2.urlopen("https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-06-03&from_station=NJH&to_station=SHH") |
| 51 | + result = resp.read() |
| 52 | + data = json.loads(result) |
| 53 | + datas = data['data']['datas'] |
| 54 | + for d in datas: |
| 55 | + if d['station_train_code'] == 'Z39': # 设置关注的车次 |
| 56 | + content = 'tickes for hard seat of %s: %s' % (d['station_train_code'], d['yz_num']) |
| 57 | + log(content) |
| 58 | + if unicode(d['yz_num']) != u"无": |
| 59 | + send_mail(content) # 如果不是“无”就发邮件通知 |
| 60 | + break |
| 61 | +except Exception, e: |
| 62 | + content = 'somethings wrong with the program:\n' + str(e) |
| 63 | + log(content) |
| 64 | + send_mail(content) # 出错时也发邮件 |
0 commit comments