Skip to content

Commit

Permalink
1. python 3 支持
Browse files Browse the repository at this point in the history
2. 日志模块替换为logging模块
  • Loading branch information
iBreaker committed Nov 17, 2017
1 parent 9586209 commit d051882
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 108 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@

*.cookies
*.pyc
.idea/
.config.yaml
188 changes: 93 additions & 95 deletions bjguahao.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,16 @@
import os
import sys
import re
import yaml
import json
import time
import datetime

import logging

from log import Log
from browser import Browser
from lib.prettytable import PrettyTable

reload(sys)
sys.setdefaultencoding( "utf-8" )

class Config(object):
"""
Expand All @@ -40,36 +39,37 @@ def load_conf(self, config_path):
加载配置
"""

try:
with open(config_path) as json_file:
data = json.load(json_file)
data = data[0]
self.mobile_no = data["username"]
self.password = data["password"]
self.date = data["date"]
self.hospital_id = data["hospitalId"]
self.department_id = data["departmentId"]
self.duty_code = data["dutyCode"]
self.patient_name = data["patientName"]
self.doctorName = data["doctorName"]

Log.info("配置加载完成")
Log.debug("手机号:" + str(self.mobile_no ))
Log.debug("挂号日期:" + str(self.date))
Log.debug("医院id:" + str(self.hospital_id))
Log.debug("科室id:" + str(self.department_id))
Log.debug("上午/下午:" + str(self.duty_code))
Log.debug("就诊人姓名:" + str(self.patient_name))

except Exception, e:
Log.exit(repr(e))
# try:
with open(config_path, "r", encoding="utf-8") as yaml_file:
data = yaml.load(yaml_file)
self.mobile_no = data["username"]
self.password = data["password"]
self.date = data["date"]
self.hospital_id = data["hospitalId"]
self.department_id = data["departmentId"]
self.duty_code = data["dutyCode"]
self.patient_name = data["patientName"]
self.doctorName = data["doctorName"]

logging.info("配置加载完成")
logging.debug("手机号:" + str(self.mobile_no ))
logging.debug("挂号日期:" + str(self.date))
logging.debug("医院id:" + str(self.hospital_id))
logging.debug("科室id:" + str(self.department_id))
logging.debug("上午/下午:" + str(self.duty_code))
logging.debug("就诊人姓名:" + str(self.patient_name))

# except Exception as e:
# logging.error(repr(e))
# exit()


class Guahao(object):
"""
挂号
"""

def __init__(self):
def __init__(self, config_path="config.yaml"):
self.browser = Browser()
self.dutys = ""
self.refresh_time = ''
Expand All @@ -81,36 +81,41 @@ def __init__(self):
self.patient_id_url = "http://www.bjguahao.gov.cn/order/confirm/"
self.department_url = "http://www.bjguahao.gov.cn/dpt/appoint/"

config = Config() # config对象
config.load_conf(config_path) # 加载配置
self.config = config
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)

def auth_login(self):
"""
登陆
"""
Log.info("开始登陆")
self.logger.info("开始登陆")
password = self.config.password
mobile_no = self.config.mobile_no
preload = {
'mobileNo': mobile_no,
'password': password,
'mobileNo': mobile_no,
'password': password,
'yzm':'',
'isAjax': True,
}
'isAjax': True,
}
response = self.browser.post(self.login_url, data=preload)
Log.debug("response data:" + response.text)
self.logger.debug("response data:" + response.text)
try:
data = json.loads(response.text)
if data["msg"] == "OK" and data["hasError"] == False and data["code"] == 200:
cookies_file = os.path.join(self.browser.root_path, self.config.mobile_no + ".cookies")
self.browser.save_cookies(cookies_file)
Log.info("登陆成功")
self.logger.info("登陆成功")
return True
else:
Log.error(data["msg"])
self.logger.error(data["msg"])
raise Exception()

except Exception, e:
Log.error("登陆失败")
Log.exit(repr(e))
except Exception as e:
self.logger.error("登陆失败")
exit()

def select_doctor(self):
"""选择合适的大夫"""
Expand All @@ -119,27 +124,27 @@ def select_doctor(self):
department_id = self.config.department_id
duty_code = self.config.duty_code
duty_date = self.config.date
# log current date
Log.debug("当前挂号日期: " + self.config.date)

# log current date
self.logger.debug("当前挂号日期: " + self.config.date)

preload = {
'hospitalId':hospital_id ,
'departmentId': department_id,
'dutyCode': duty_code,
'dutyDate': duty_date,
'isAjax': True
'isAjax': True
}
response = self.browser.post(self.get_doctor_url , data=preload)
Log.debug("response data:" + response.text)
self.logger.debug("response data:" + response.text)

try:
data = json.loads(response.text)
if data["msg"] == "OK" and data["hasError"] == False and data["code"] == 200:
self.dutys = data["data"]

except Exception, e:
Log.exit(repr(e))
except Exception as e:
self.logger.exit(repr(e))

if len(self.dutys) == 0:
return "NotReady"
Expand All @@ -148,23 +153,23 @@ def select_doctor(self):

for doctor in self.dutys[::-1]:
if doctor["doctorName"] == self.config.doctorName and doctor['remainAvailableNumber']:
Log.info(u"选中:" + str(doctor["doctorName"]))
self.logger.info(u"选中:" + str(doctor["doctorName"]))
return doctor
for doctor in self.dutys[::-1]:
if doctor['remainAvailableNumber']:
Log.info(u"选中:" + str(doctor["doctorName"]))
self.logger.info(u"选中:" + str(doctor["doctorName"]))
return doctor
return "NoDuty"

def print_doctor(self):

Log.info("当前号余量:")
self.logger.info("当前号余量:")
x = PrettyTable()
x.border = True
x.field_names = ["医生姓名", "擅长", "号余量"]
for doctor in self.dutys:
x.add_row([doctor["doctorName"], doctor['skill'], doctor['remainAvailableNumber']])
print x.get_string()
print(x.get_string())
pass

def get_it(self, doctor, sms_code):
Expand All @@ -188,22 +193,22 @@ def get_it(self, doctor, sms_code):
"reimbursementType":"10", # 报销类型
'smsVerifyCode': sms_code, # TODO 获取验证码
'childrenBirthday':"",
'isAjax': True
'isAjax': True
}
response = self.browser.post(self.confirm_url , data=preload)
Log.debug("response data:" + response.text)
self.logger.debug("response data:" + response.text)

try:
data = json.loads(response.text)
if data["msg"] == "OK" and data["hasError"] == False and data["code"] == 200:
Log.info("挂号成功")
self.logger.info("挂号成功")
return True
else:
Log.error(data["msg"])
self.logger.error(data["msg"])
return False

except Exception, e:
Log.error(repr(e))
except Exception as e:
self.logger.error(repr(e))
time.sleep(1)


Expand All @@ -224,7 +229,7 @@ def get_patient_id(self, doctor):
exit("获取患者id失败")
else:
self.config.patient_id = m.group('patientId')
Log.info( "病人ID:" + self.config.patient_id)
self.logger.info( "病人ID:" + self.config.patient_id)

return self.config.patient_id

Expand All @@ -246,66 +251,61 @@ def get_duty_time(self):
appoint_day = m.group('appointDay')

today = datetime.date.today()
# 优先确认最新可挂号日期

# 优先确认最新可挂号日期
self.stop_date = today + datetime.timedelta(days=int(appoint_day))
Log.info("今日可挂号到: " + self.stop_date.strftime("%Y-%m-%d"))
# 自动挂最新一天的号
self.logger.info("今日可挂号到: " + self.stop_date.strftime("%Y-%m-%d"))

# 自动挂最新一天的号
if self.config.date == 'latest':
self.config.date = unicode(self.stop_date.strftime("%Y-%m-%d"))
Log.info("当前挂号日期变更为: " + self.config.date)
self.config.date = self.stop_date.strftime("%Y-%m-%d")
self.logger.info("当前挂号日期变更为: " + self.config.date)

# 生成放号时间和程序开始时间
con_data_str = self.config.date + " " + refresh_time + ":00"
self.start_time = datetime.datetime.strptime(con_data_str, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(days= - int(appoint_day))
Log.info("放号时间: " + self.start_time.strftime("%Y-%m-%d %H:%M"))
self.start_time = datetime.datetime.strptime(con_data_str, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(days= - int(appoint_day))
self.logger.info("放号时间: " + self.start_time.strftime("%Y-%m-%d %H:%M"))

def get_sms_verify_code(self):
"""获取短信验证码"""
response = self.browser.post(self.send_code_url, "")
data = json.loads(response.text)
Log.debug(response.text)
self.logger.debug(response.text)
if data["msg"] == "OK." and data["code"] == 200:
Log.info("获取验证码成功")
self.logger.info("获取验证码成功")
return raw_input("输入短信验证码: ")
elif data["msg"] == "短信发送太频繁" and data["code"] == 812:
Log.exit(data["msg"])
self.logger.exit(data["msg"])
else:
Log.error(data["msg"])
self.logger.error(data["msg"])
return None

def run(self, config_path):
def run(self):
"""主逻辑"""

config = Config() # config对象
config.load_conf(config_path) # 加载配置
self.config = config
self.get_duty_time()


self.auth_login() # 1. 登陆
curTime = datetime.datetime.now() + datetime.timedelta(seconds=int(time.timezone + 8*60*60))
curTime = datetime.datetime.now() + datetime.timedelta(seconds=int(time.timezone + 8*60*60))

if self.start_time > curTime:
seconds = (self.start_time - curTime).total_seconds()
Log.info("距离放号时间还有" + str(seconds) + "秒")
self.logger.info("距离放号时间还有" + str(seconds) + "秒")
sleep_time = seconds - 60
if sleep_time > 0:
Log.info("程序休眠" + str(sleep_time) + "秒后开始运行")
self.logger.info("程序休眠" + str(sleep_time) + "秒后开始运行")
time.sleep(sleep_time)
# 自动重新登录
if sleep_time > 1000:
self.auth_login()
# 自动重新登录
if sleep_time > 1000:
self.auth_login()

doctor = "";
while True:
doctor = self.select_doctor() # 2. 选择医生
self.get_patient_id(doctor) # 3. 获取病人id
self.get_patient_id(doctor) # 3. 获取病人id
if doctor == "NoDuty":
Log.error("没号了, 亲~")
self.logger.error("没号了, 亲~")
break
elif doctor == "NotReady":
Log.info("好像还没放号?重试中")
self.logger.info("好像还没放号?重试中")
time.sleep(1)
else:
sms_code = self.get_sms_verify_code() # 获取验证码
Expand All @@ -317,13 +317,11 @@ def run(self, config_path):
break # 挂号成功

if __name__ == "__main__":
# 生成默认 config 地址
config_path = 'config.json'

# 覆盖 config 地址
for i in range(1, len(sys.argv)):
if (sys.argv[i] == '-c') & (i+1 < len(sys.argv)):
config_path = sys.argv[i+1]
Log.load_config(config_path)
guahao = Guahao()
guahao.run(config_path)

if (len(sys.argv) == 3) and (sys.argv[1] == '-c') and (isinstance(sys.argv[2], str)):
config_path = sys.argv[2]
guahao = Guahao(config_path)
else:
guahao = Guahao()
guahao.run()

Loading

0 comments on commit d051882

Please sign in to comment.