用python登錄12306 並保存cookie


  一篇拿來記錄的文章,是看其他博主寫的,想在這記一下

  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"

  }鄭州做人流手術要多少錢 http://www.sptdnk.com/

  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]

  免責聲明:僅限用於學習和研究目的;不得將上述內容用於商業或者非法用途,否則,一切后果請用戶自負。您必須在下載后的24個小時之內,從您的電腦或手機中徹底刪除上述內容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM