python实现12306登录并保存cookie的方法示例


Posted in Python onDecember 17, 2019

经过倒腾12306的登录,还是实现了,请求头很重要...各位感兴趣的可以继续写下去.....

import sys
import time
import requests
from PIL import Image
import json
import os
import Headers
import SessionUtil
import UrlUtils
 
class Ticket(object):
  def __init__(self):
    self.answer = {
      "1": "40,40",
      "2": "110,40",
      "3": "180,40",
      "4": "260,40",
      "5": "40,120",
      "6": "110,120",
      "7": "180,120",
      "8": "260,120",
    }
    self.answer_code=''
    self.tk = ''
 
  def getDEVICEID(self):
    r = requests.get(UrlUtils.DEVICE_url, headers=Headers.BaseHead).text
    try:
      dic = json.loads(r[18:-2].replace(" ", ""))
    except Exception:
      return ""
    return dic
 
  # 初始化 获取设备id 设置为cookie 必须
  def initialize(self):
    dic = self.getDEVICEID()
    if dic == "":
      print("网络获取指纹失败!使用默认id")
      RAIL_EXPIRATION = "1576651914389"
      RAIL_DEVICEID = "lBJStCNl0YGo_HVkGtwOo2LWziXcwzpIk5gc2vAILNYdRfaeZ04nJtZ1JZwgQIssMDksn10rAz6Hz-bekeufhAusaKJId8f2BCg05ocgrzc8-chv8h4IB-lQ9H04XjLXr2fbnHw-SLZga3PewEfgPz2s-mhp7NAz"
    else:
      print("网络获取指纹成功!")
      RAIL_EXPIRATION = dic["exp"]
      RAIL_DEVICEID = dic['dfp']
    SessionUtil.setCookie("RAIL_EXPIRATION", RAIL_EXPIRATION)
    SessionUtil.setCookie("RAIL_DEVICEID", RAIL_DEVICEID)
 
  def conf(self):
    res = SessionUtil.session.post(url=UrlUtils.Conf_url, data=None, headers=Headers.ConFHeader)
 
  def uamtkstatic(self):
    data = {
      'appid': 'otn'
    }
    SessionUtil.session.post(url=UrlUtils.UamtkStatic_url, data=data, headers=Headers.UamtkStaticHead)
 
  def get_img_code(self):
    try:
      img = SessionUtil.session.get(url=UrlUtils.Down_mg_url, headers=Headers.BaseHead).content
      with open('code.jpg', 'wb') as f:
        f.write(img)
    except Exception:
      print("下载图片错误! 等待重试~~")
      time.sleep(1)
      self.get_img_code()
 
  def check_img(self):
    try:
      Image.open('code.jpg').show()
    except Exception:
      time.sleep(2)
      Image.open('code.jpg').show()
    print("+---1-------+----------+----------+----------+")
    print("|  1   |  2   |  3   |  4   |")
    print("|----------|----------|----------|----------|")
    print("|  5   |  6   |  7   |  8   |")
    print("+----------+----------+----------+----------+")
    input_code = input("请在1—8中选择输入验证图片编号,以半角','隔开。(例如:1,3,5):")
    answer_code = ''
    try:
      for i in input_code.split(','):
        answer_code += ',' + self.answer[i] if (i is not input_code[0]) else self.answer[i]
    except Exception as e:
      print('输入错误请重新输入!')
      self.check_img()
    data = {
      'answer': answer_code,
      'rand': 'sjrand',
      'login_site': 'E',
    }
    response = SessionUtil.session.get(url=UrlUtils.Check_img_url, params=data, headers=Headers.BaseHead, )
    check_result = json.loads(response.text)
    print(check_result)
    try:
      if check_result['result_code'] == '4':
        print('*' * 20 + '验证码正确' + '*' * 20)
        self.answer_code=answer_code
      else:
        self.get_img_code()
        self.check_img()
    except Exception:
      self.get_img_code()
      self.check_img()
 
  # 校验密码正确
  def login(self, answer_code):
    user = ''
    password = ''
    try:
      with open("user.conf", "r", encoding="utf-8") as f:
        user = f.readline().strip().replace("[", '').replace("]", '').replace("name=", '')
        password = f.readline().strip().replace("[", '').replace("]", '').replace("pwd=", '')
        if user == "" or password == "":
          raise Exception
    except Exception:
      user = input("账号____:")
      password = input("密码____:")
 
    formdata = {
      'username': user,
      'password': password,
      'appid': 'otn',
      'answer': answer_code
    }
    login_result = SessionUtil.session.post(url=UrlUtils.Login_url, data=formdata, headers=Headers.BaseHead)
    login_result.encoding = 'utf-8'
    login_result = login_result.json()
    print(login_result)
    if login_result["result_code"] != 0: #{'result_message': '登录名不存在。', 'result_code': 1}
      sys.exit(0)
 
  # 二次校验
  def userLogin(self):
    # 获取一系列的cookie值才能真正的登录成功
    response = SessionUtil.session.get(url=UrlUtils.UserLogin_url, headers=Headers.UserLoginHead)
    # 更新JSESSIONID route
    response = SessionUtil.session.get(url=UrlUtils.Redirect_UserLogin_Url, headers=Headers.RedirectHead)
 
  def uamtk(self):
    # 获取 tk 下一个请求需要提交 tk 值
    data = {'appid': 'otn'}
    uamtk_page = SessionUtil.session.post(url=UrlUtils.Uamtk_url, data=data, headers=Headers.UamtkHeader)
    uamtk_page.encoding = 'utf-8'
    try:
      result = uamtk_page.json()
      print(result)
      if result['result_code'] != 0:
        raise Exception(result['result_message'])
      tk = result['newapptk']
      self.tk = tk
    except Exception:
      print("获取tk失败!")
      print("重试")
      self.run()
 
  def Uamauthclient(self):
    data = {'tk': self.tk}
    response = SessionUtil.session.post(url=UrlUtils.Uamauthclient_url, data=data,
                      headers=Headers.UamauthclientHeader)
    res = response.text
    try:
      dic = json.loads(res)
      print(dic)
      print(dic["username"] + ",欢迎登录!")
    except:
      print("登录失败!")
      self.run()
    # '{"result_code":0,"result_message":"验证通过","username":"XXX","apptk":"36yslXHez3_68-LtHvhI61mZkranjdw6kT9j4UMwEqrw1w0"}'
 
  def saveCookie(self):
    SessionUtil.save_cookies("12306cookies.txt")
 
  def getInfo(self):
 
    try:
      re = SessionUtil.session.post("https://kyfw.12306.cn/otn/modifyUser/initQueryUserInfoApi",
                     headers=Headers.UserInfoHead)
      print(re.text)
    except:
      print("获取失败")
 
  def run(self):
    self.initialize()
    self.conf()
    self.uamtkstatic()
    self.get_img_code()
    self.check_img()
    self.login(self.answer_code)
    self.userLogin()
    self.uamtk()
    self.Uamauthclient()
    self.saveCookie()
    self.conf()
    self.getInfo()
 
 
if __name__ == '__main__':
  t = Ticket()
  result = "":
  try:
     with open("12306cookies.txt", "r", encoding="utf-8") as fr:
      result = fr.read()
   except Exception:
     pass
  if result != "":
    SessionUtil.load_cookies("12306cookies.txt")
    t.initialize()
    t.conf()
    t.uamtkstatic()
    t.userLogin()
    t.uamtk()
    t.Uamauthclient()
    t.getInfo()
  else:
    t.run()

Headers:

BaseHead = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  "Host": "kyfw.12306.cn",
  "Referer": "https://kyfw.12306.cn/otn/resources/login.html"
}
 
UserLoginHead = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  'Content-Type': 'application/x-www-form-urlencoded',
  'Referer': 'https://kyfw.12306.cn/otn/resources/login.html',
  'Upgrade-Insecure-Requests': '1',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}
RedirectHead = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  'Referer': 'https://kyfw.12306.cn/otn/resources/login.html',
  'Upgrade-Insecure-Requests': '1',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
 
}
 
UamtkHeader = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'Referer': 'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept': r'application/json, text/javascript, */*; q=0.01',
  'Origin': 'https://kyfw.12306.cn'
}
 
UamauthclientHeader = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  "Host": "kyfw.12306.cn",
  'Referer': r'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin',
}
ConFHeader = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  "Host": "kyfw.12306.cn",
  "Referer": "https://kyfw.12306.cn/otn/resources/login.html"
}
 
UamtkStaticHead = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  'Referer': 'https://kyfw.12306.cn/otn/resources/login.html',
}
 
UserInfoHead = {
  "Accept": "*/*",
  "Accept-Encoding": "gzip, deflate, br",
  "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  "Cache-Control": "no-cache",
  "Connection": "keep-alive",
  "Content-Length": "0",
  "Host": "kyfw.12306.cn",
  "Origin": "https://kyfw.12306.cn",
  "Pragma": "no-cache",
  "Referer": "https://kyfw.12306.cn/otn/view/information.html",
  "Sec-Fetch-Mode": "cors",
  "Sec-Fetch-Site": "same-origin",
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest",
}

SessionUtil

import requests
import urllib3
from http import cookiejar
urllib3.disable_warnings()
session = requests.Session()
session.verify = False # 取消验证 SSL
 
def setCookie(key,value):
  session.cookies.set(key,value)
 
 
def removeCookies(key=None):
  session.cookies.set(key, None) if key else session.cookies.clear()
 
 
def load_cookies(cookie_path="12306cookies.txt"):
  load_cookiejar = cookiejar.LWPCookieJar()
  load_cookiejar.load(cookie_path, ignore_discard=True, ignore_expires=True)
  load_cookies = requests.utils.dict_from_cookiejar(load_cookiejar)
  session.cookies = requests.utils.cookiejar_from_dict(load_cookies)
 
def save_cookies(cookie_path="12306cookies.txt"):
  new_cookie_jar = cookiejar.LWPCookieJar(cookie_path)
  requests.utils.cookiejar_from_dict({c.name: c.value for c in session.cookies}, new_cookie_jar)
  new_cookie_jar.save(cookie_path, ignore_discard=True, ignore_expires=True)

UrlUtils

import time
DEVICE_url= 'https://kyfw.12306.cn/otn/HttpZF/logdevice?algID=cS6Aw4inWV&hashCode=lZGX9bmwQGHuZPviiiBCrtoNPyHZ4pBG3jvF2dybZ6o&FMQw=0&q4f3=zh-CN&VySQ=FGGxHVb3AzlSM-oikvoZfGsTbD48DQud&VPIf=1&custID=133&VEek=unknown&dzuS=32.0 r0&yD16=0&EOQP=38437f3289ca7a613bb292a3de0dba2b&jp76=df7f80581243b062f0c64efc90666cd0&hAqN=Win32&platform=WEB&ks0Q=7523081fcf2454464b148398defb390a&TeRS=864x1536&tOHY=24xx864x1536&Fvje=i1l1o1s1&q5aJ=-8&wNLf=99115dfb07133750ba677d055874de87&0aew=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36&E3gR=7a13398746be6f51fe069c8a25001f12×tamp=' + str(round(time.time() * 1000))
 
#验证码下载地址
Down_mg_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&{}'.format(int(time.time() * 1000))
 
#验证码 验证地址
Check_img_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
#登录地址 校验账号密码
Login_url = 'https://kyfw.12306.cn/passport/web/login'
 
#二次校验
UserLogin_url = 'https://kyfw.12306.cn/otn/login/userLogin'
 
#重定向二次校验
Redirect_UserLogin_Url = 'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin'
 
#获取 tk关键 url
Uamtk_url = 'https://kyfw.12306.cn/passport/web/auth/uamtk'
 
# 使用tk 校验
Uamauthclient_url = 'https://kyfw.12306.cn/otn/uamauthclient'
 
#使用cookie直接 请求这个就可以访问 api
Conf_url = 'https://kyfw.12306.cn/otn/login/conf'
 
 
UamtkStatic_url = 'https://kyfw.12306.cn/passport/web/auth/uamtk-static'
 
initMy12306Api_url="https://kyfw.12306.cn/otn/index/initMy12306Api"[/mw_shl_code]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现备份文件实例
Sep 16 Python
Python实现数据库编程方法详解
Jun 09 Python
python通过文件头判断文件类型
Oct 30 Python
python中找出numpy array数组的最值及其索引方法
Apr 17 Python
python学生管理系统开发
Jan 30 Python
python通过paramiko复制远程文件及文件目录到本地
Apr 30 Python
简单的Python调度器Schedule详解
Aug 30 Python
浅谈Python的方法解析顺序(MRO)
Mar 05 Python
学习Python列表的基础知识汇总
Mar 10 Python
什么是python类属性
Jun 10 Python
Python中return函数返回值实例用法
Nov 19 Python
python中的时区问题
Jan 14 Python
Django多进程滚动日志问题解决方案
Dec 17 #Python
python django中8000端口被占用的解决
Dec 17 #Python
python飞机大战pygame游戏之敌机出场实现方法详解
Dec 17 #Python
解决pycharm上的jupyter notebook端口被占用问题
Dec 17 #Python
解决python web项目意外关闭,但占用端口的问题
Dec 17 #Python
selenium+Chrome滑动验证码破解二(某某网站)
Dec 17 #Python
python飞机大战 pygame游戏创建快速入门详解
Dec 17 #Python
You might like
php入门之连接mysql数据库的一个类
2012/04/21 PHP
Erlang的运算符(比较运算符,数值运算符,移位运算符,逻辑运算符)
2012/07/23 PHP
php中get_headers函数的作用及用法的详细介绍
2013/04/27 PHP
ThinkPHP实现跨模块调用操作方法概述
2014/06/20 PHP
解析WordPress中控制用户登陆和判断用户登陆的PHP函数
2016/03/01 PHP
深入理解PHP原理之执行周期分析
2016/06/01 PHP
Laravel框架定时任务2种实现方式示例
2018/12/08 PHP
使用SMB共享来绕过php远程文件包含的限制执行RFI的利用
2019/05/31 PHP
基于Web标准的UI组件 — 树状菜单(2)
2006/09/18 Javascript
基于jquery实现的移入页面上空文本框时,让它变为焦点,移出清除焦点
2011/07/26 Javascript
解决js正则匹配换行问题实现代码
2012/12/10 Javascript
关于JavaScript与HTML的交互事件
2013/04/12 Javascript
JavaScript中的逻辑判断符&&、||与!介绍
2014/12/31 Javascript
js使用DOM操作实现简单留言板的方法
2015/04/10 Javascript
Javascript实现图片懒加载插件的方法
2016/10/20 Javascript
javascript实现获取图片大小及图片等比缩放的方法
2016/11/24 Javascript
React BootStrap用户体验框架快速上手
2018/03/06 Javascript
如何在JavaScript中优雅的提取循环内数据详解
2019/03/04 Javascript
深入了解js原型模式
2019/05/30 Javascript
vue使用高德地图根据坐标定位点的实现代码
2019/08/22 Javascript
JS 设计模式之:单例模式定义与实现方法浅析
2020/05/06 Javascript
JS如何调用WebAssembly编译出来的.wasm文件
2020/11/05 Javascript
[01:33]一分钟玩转DOTA2第三弹:DOTA2&DotA快捷操作大对比
2014/06/04 DOTA
[26:50]2018完美盛典DOTA2表演赛
2018/12/17 DOTA
[01:04:05]Mineski vs TNC 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
python中的yield使用方法
2014/02/11 Python
Python3实现简单可学习的手写体识别(实例讲解)
2017/10/21 Python
python 判断字符串中是否含有汉字或非汉字的实例
2019/07/15 Python
为什么黑客都用python(123个黑客必备的Python工具)
2020/01/31 Python
Python *args和**kwargs用法实例解析
2020/03/02 Python
Python钉钉报警及Zabbix集成钉钉报警的示例代码
2020/08/17 Python
Python 里最强的地图绘制神器
2021/03/01 Python
2014年纪检工作总结
2014/11/12 职场文书
工会文体活动总结
2015/05/07 职场文书
九年级英语教学反思
2016/02/15 职场文书
科学家研发出新型速效酶,可在 24 小时内降解塑料制品
2022/04/29 数码科技