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

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

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

(0)

相关推荐

  • Python Selenium Cookie 绕过验证码实现登录示例代码

    之前介绍过通过cookie 绕过验证码实现登录的方法.这里并不多余,会增加分析和另外一种方法实现登录. 1.思路介绍  1.1.直接看代码,内有详细注释说明 # FileName : Wm_Cookie_Login.py # Author : Adil # DateTime : 2018/3/20 19:47 # SoftWare : PyCharm from selenium import webdriver import time url = 'https://system.address'

  • Python3 Post登录并且保存cookie登录其他页面的方法

    如下所示: import urllib.request import sys import http.cookiejar import urllib.parse from bs4 import BeautifulSoup import codecs import re #登录页面 url = "http://www.abc.com/login.asp" #登录Post数据 postdata =urllib.parse.urlencode({ "username":&

  • python模拟登录并且保持cookie的方法详解

    前言 最近在爬行 nosec.org 的数据,看了下需要模拟登录拿到cookie后才能访问想抓的数据,重要的是 nosec.org 的登录页面 form 中有个 authenticity_token 字段每次访问登录页面都会自动生成,而且会和你的用户名,密码一样被POST到服务器. 经过一番研究后发现,直接访问网站登录界面的时候,服务器的响应头会有一个Set-Cookie字段,如下: _nosec_session=ZTlHNmxuZXE4R0s1UXpsVUxGRTNPblNBWFd2TXU4T

  • python通过cookie模拟已登录状态的初步研究

    对于那些需要在登录环境下进行的爬虫操作,模拟登陆或伪装已登录状态是一个刚需. 分析了网上关于模拟登录的例子,很多都基于用户名/密码发起一个post请求,遇到有图片验证码的,比较理想的方法是进行人工干预,同步发起一个图片验证码的请求,将图片写到本地,人工查看后进行输入. 既然,少不了人工干预,为何登录操作不全程人工进行,已登录后再把浏览器的Cookie信息全拷贝出来,通过爬虫伪造成一个已登录的浏览器呢? 我暂时试了试国内的几个大网站,发现都行得通,可以模拟浏览器进行登录之后的很多操作,包括签到,修

  • python 利用浏览器 Cookie 模拟登录的用户访问知乎的方法

    首先在火狐浏览器上登录知乎,然后使用火狐浏览器插件 Httpfox 获取 GET 请求的Cookie,这里注意使用状态值为 200(获取成功)的某次GET. 将 Cookies 复制出来,注意这一行非常长,不要人为添加换行符.而且 Cookie 中使用了双引号,最后复制到代码里使用单引号包起来. 使用下边代码检验是否是模拟了登录的用户的请求: import requests import re headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT

  • python爬虫使用cookie登录详解

    前言: 什么是cookie? Cookie,指某些网站为了辨别用户身份.进行session跟踪而储存在用户本地终端上的数据(通常经过加密). 比如说有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个页面内容是不允许的.那么我们可以利用Urllib库保存我们登录的Cookie,然后再抓取其他页面,这样就达到了我们的目的. 一.Urllib库简介 Urllib是python内置的HTTP请求库,官方地址:https://docs.python.org/3/library/urllib.ht

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

    经过倒腾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": &q

  • Python 实现12306登录功能实例代码

    下面一段代码给大家带来了python实现12306登录功能,具体代码如下所示: #!/usr/bin/env python import requests import urllib.parse import random import time req = requests.session() import sys import re import urllib3 import getpass # 密文输入 urllib3.disable_warnings() # 登陆------------

  • python解决12306登录验证码的实现

    在家无聊,线代和高数看不懂,整点事情干,就准备预定回学校的高铁票,于是就有了这个文章 准备工作 1.pip安装chromediver,当然也可以手动解压(网上的教程好像没有提到pip,手动安装到C盘pycharm里面的Scripts就行了) chromedriver.storage.googleapis.com/index.html这是chromedriver文件官网,在chrome里面设置查看自己的版本,然后找对应的版本就完了 2.注册个超级鹰,http://www.chaojiying.co

  • python通过ftplib登录到ftp服务器的方法

    本文实例讲述了python通过ftplib登录到ftp服务器的方法.分享给大家供大家参考.具体实现方法如下: import ftplib connect = ftplib.FTP("www.mysite.com") connect.login("domain\user", "password") data = [] connect.dir(data.append) connect.quit() for line in data: print(li

  • linux expect 自动登录交换机保存配置的方法

    telnet.exp 文件内容如下: #!/usr/bin/expect -f set ip [lindex $argv 0 ] set username [lindex $argv 1 ] set password [lindex $argv 2 ] set superpassword [lindex $argv 3 ] set timeout 10 spawn telnet $ip expect { "name" { send "$username\r";exp

  • Python编程给numpy矩阵添加一列方法示例

    首先我们有一个数据是一个mn的numpy矩阵现在我们希望能够进行给他加上一列变成一个m(n+1)的矩阵 import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = np.ones(3) c = np.array([[1,2,3,1],[4,5,6,1],[7,8,9,1]]) PRint(a) print(b) print(c) [[1 2 3] [4 5 6] [7 8 9]] [ 1. 1. 1.] [[1 2 3 1] [4

  • python 比较2张图片的相似度的方法示例

    本文介绍了python 比较2张图片的相似度的方法示例,分享给大家,具体如下: #!/usr/bin/python # -*- coding: UTF-8 -*- import cv2 import numpy as np #均值哈希算法 def aHash(img): #缩放为8*8 img=cv2.resize(img,(8,8),interpolation=cv2.INTER_CUBIC) #转换为灰度图 gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

  • Python中使用socks5设置全局代理的方法示例

    0x01介绍 PySocks使您可以通过SOCKS和HTTP代理服务器发送流量.它是SocksiPy的现代分支,具有错误修复和其他功能. 0x02 安装 λ pip3 install Pysocks 0x03 测试 正常请求,httperror无法获得 加入socks5代理后,可以获得当前程序的全局代理可以 正常访问 import socket import socks socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 10808)

  • python入门turtle库实现螺旋曲线图的方法示例

    记录turtle库中经常用到的函数. turtle.forward(distance)  画笔向前移动distance距离 turtle.backforward(distance)  画笔向后移动distance距离 turtle.right(degree)  绘制方向向右旋转degree度 turtle.exitonclick()  点击关闭图形窗口 turtle.penup()   抬起画笔,之后移动画笔不绘制形状 turtle.pendown()  落下画笔,之后移动画笔绘制形状 turt

随机推荐