经过倒腾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()

python 12306登录 2019_python实现12306登录并保存cookie的方法示例相关推荐

  1. python过去日期_利用python获取当前日期前后N天或N月日期的方法示例

    前言 最近因为工作原因,发现一个Python的时间组件,很好用分享出来!(忘记作者名字了,在这里先感谢了),下面话不多说,来一起看看详细的介绍吧. 示例代码: # -*- coding: utf-8 ...

  2. python求数字平均值_Python简单计算数组元素平均值的方法示例

    本文实例讲述了Python简单计算数组元素平均值的方法.分享给大家供大家参考,具体如下: Python 环境:Python 2.7.12 x64 IDE : Wing IDE Professional ...

  3. python 字符串替换多个_python同时替换多个字符串方法示例

    本文介绍了python同时替换多个字符串方法示例,分享给大家,具体如下: import re words = ''' 钟声响起归家的讯号 在他生命里 仿佛带点唏嘘 黑色肌肤给他的意义 是一生奉献 肤色 ...

  4. python socks代理_Python中使用socks5设置全局代理的方法示例

    0x01介绍 PySocks使您可以通过SOCKS和HTTP代理服务器发送流量.它是SocksiPy的现代分支,具有错误修复和其他功能. 0x02 安装 λ pip3 install Pysocks ...

  5. python判断天数_Python计算两个日期相差天数的方法示例

    本文实例讲述了Python计算两个日期相差天数的方法.分享给大家供大家参考,具体如下: #!/usr/bin/python import time import sys def dateinput() ...

  6. python 下载视频文件_python 实现视频流下载保存MP4的方法

    如下所示: # -*- coding:utf-8 -*- import sys import os from glob import glob import requests reload(sys) ...

  7. python辗转相除_Python基于辗转相除法求解最大公约数的方法示例

    Python基于辗转相除法求解最大公约数的方法示例 本文实例讲述了Python基于辗转相除法求解最大公约数的方法.分享给大家供大家参考,具体如下: 之前总结过一次高德纳TAOCP中的最大公约数求解,其 ...

  8. python selenium爬虫实例_python使用selenium爬虫知乎的方法示例

    说起爬虫一般想到的情况是,使用 python 中都通过 requests 库获取网页内容,然后通过 beautifulSoup 进行筛选文档中的标签和内容.但是这样有个问题就是,容易被反扒机制所拦住. ...

  9. python 12306登录 2019_Python 实现12306登录功能实例代码

    下面一段代码给大家带来了python实现12306登录功能,具体代码如下所示: #!/usr/bin/env python import requests import urllib.parse im ...

最新文章

  1. Android Html.fromHtml 的使用
  2. 211高校副校长:我发了170多篇论文,最满意的一篇不到2分
  3. 【其他】GIT常用原生命令
  4. 题目1186:打印日期
  5. 基于MVC4+EasyUI的Web开发框架经验总结(13)--DataGrid控件实现自己主动适应宽带高度...
  6. 安全管家安卓_pc-cillin和腾讯电脑管家比较哪个更好
  7. 03 ORA系列:ORA-00942 表或视图不存在 table or view does not exist
  8. 裸板烧写 bootloader
  9. Python命令行参数解析模块getopt使用实例
  10. wxWidgets:启动默认浏览器
  11. Python中装饰器的理解和实现
  12. JDK14性能管理工具:Jconsole详解
  13. List 集合remove问题
  14. C++ string assign()赋值常用方法
  15. 如何使用Bash将stdout和stderr重定向并附加到文件?
  16. 维度模型数据仓库基础对象概念一览
  17. k3c路由怎么设置虚拟服务器,搭建ngrok服务器!!给k3.k3c.K2.k2p路由器使用!!详细教程!!!...
  18. Android系统关于音量相关的控制-初识
  19. jquery name选择器
  20. WebRTC 非常适用于智能家庭安防摄像头

热门文章

  1. android调用wcf服务的xml,Android调用WCF
  2. 水墨屏RFID超高频标签|RFID电子纸之组态软件操作说明2
  3. [日常笔记] 2: 本地视频播放器 MPV
  4. esp32的python教程步数采集_ESP32CAM micropython的操作指南
  5. C版的迷你程序——快速排序算法
  6. 图文详解在Windows系统中安装JDK
  7. Life feelings--11--护眼贴士-如何让心灵的窗口锃光发亮?-程序员工程师生活必备
  8. java用mysql方便吗_面试题总结:可能是全网最好的MySQL重要知识点
  9. 小爬虫爬取小猫咪图片并存入本地文件夹
  10. 【7.0】 数学建模 | 相关系数详解 | Person相关系数、Spearman相关系数