crawl_12306.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2023/07/11 20:25:17
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc :
  8. '''
  9. import argparse,time,json
  10. import base64
  11. from email.mime.text import MIMEText
  12. from email.header import Header
  13. import os,sys,re,configparser,logging,requests
  14. import smtplib,random
  15. from fuck12306 import api
  16. class Crawl12306:
  17. ''' 12306 抢票助手 '''
  18. def __init__(self):
  19. self.sess=requests.Session()
  20. self.args=self.get_args()
  21. self.conf=self.get_conf()
  22. def set_log(self):
  23. logging.basicConfig()
  24. def get_conf(self)->dict:
  25. ''' read config.ini and return a dict'''
  26. cf = configparser.ConfigParser()
  27. cf.read("conf/config.ini")
  28. return cf
  29. def get_args(self):
  30. parser=argparse.ArgumentParser(description='12306 抢票助手')
  31. parser.add_argument('-d','--date',help='出发日期')
  32. parser.add_argument('-f','--from',help='出发地')
  33. parser.add_argument('-t','--to',help='目的地')
  34. parser.add_argument('-m','--mail',help='接收通知的邮箱')
  35. parser.add_argument('-c','--config',help='配置文件')
  36. return parser.parse_args()
  37. def get_code_pic(self, number=100):
  38. ''' get code picture '''
  39. print("............... get code pic ...........")
  40. for i in range(number):
  41. print("-----------%s--------------" % (i))
  42. # 设置代理
  43. proxies = {
  44. "http": "http://" + self.conf["proxy"]["proxy"],
  45. "https": "https://" + self.conf["proxy"]["proxy"],
  46. }
  47. self.sess.proxies.update(proxies)
  48. res = self.sess.get(api.pic_new_url)
  49. time.sleep(random.randint(3,5))
  50. if res.status_code == 200:
  51. with open("data/pic/pic_%s%s.png" % (int(time.time()), i), "wb") as file:
  52. file.write(res.content)
  53. def get_code_pic2(self, number=100):
  54. ''' get code picture old api '''
  55. print("............... get code pic ...........")
  56. for i in range(number):
  57. print("-----------%s--------------" % (i))
  58. res= self.sess.get(api.pic_old_url)
  59. time.sleep(random.uniform(0.5, 1))
  60. if res.status_code == 200:
  61. img_str = json.loads(res.content)['image']
  62. with open("data/pic2/pic_%s%s.png" % (int(time.time()), i), "wb") as file:
  63. file.write(base64.b64decode(img_str))
  64. def monitor(self):
  65. ''' 监控余票 '''
  66. print("余票监控中...")
  67. while True:
  68. try:
  69. res=self.sess.get(self.conf["url"]["left_ticket_url"])
  70. if res.status_code == 200:
  71. j = json.loads(r.text)
  72. k = j['data']
  73. str1 = ""
  74. strData = ["G6305","D7501","G6325","D7521","D7533","D7529","D2381","G6337","D7525","G6321","D7513","G6313","G1607","G6309","D7533","D7517","G6329","D7505","G6345","G6341"]
  75. for r in k['result']:
  76. for cs in strData:
  77. if "|" + cs+"|" in r:
  78. if r.split('|')[-7] != '无': #二等座
  79. str1 = str1 + cs + ',有票啦~~\n'
  80. if len(str1)>5:
  81. print(str1)
  82. self.send_mail(str1)
  83. sys.stdout.write('\r')
  84. sys.stdout.write('已查询%d次~' % self.num)
  85. sys.stdout.flush()
  86. self.num+=1
  87. else:
  88. self.send_mail("获取车票信息失败~~")
  89. except Exception as e:
  90. pass
  91. finally:
  92. pass
  93. time.sleep(5,10)
  94. self.send_mail('有票了')
  95. def send_mail(self, content: str):
  96. ''' send mail '''
  97. message = MIMEText(content, 'plain', 'utf-8')
  98. message['From'] = Header("肥肥", 'utf-8')
  99. message['To'] = Header("圆圆", 'utf-8')
  100. message['Subject'] = Header("余票提醒", 'utf-8')
  101. try:
  102. smtpObj = smtplib.SMTP()
  103. smtpObj.connect(self.conf["mail"]["host"], 25) # 25 为 SMTP 端口号
  104. smtpObj.login(self.conf["mail"]["user"], self.conf["mail"]["password"])
  105. smtpObj.sendmail(self.conf["mail"]["sender"], self.conf["mail"]["receiver"], message.as_string())
  106. print("邮件发送成功")
  107. except Exception as e:
  108. print("Error: 无法发送邮件")
  109. finally:
  110. pass
  111. @staticmethod
  112. def check_update():
  113. ''' check application update '''
  114. pass