码迷,mamicode.com
首页 > 其他好文 > 详细

requests 获取token

时间:2018-08-20 14:30:54      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:ati   content   upd   rand   cookies   type   phone   ret   for   

# encoding:utf-8

import re
import json
import random
from requests.sessions import Session


class Regist(object):
  def __init__(self):
    """初始化session 并设置header和cookie"""

    self.url = "http://xxxx/Account/Regist"
    self.s = Session()
    self.s.headers.setdefault("Content_type", "application/x-www-form-urlencoded")
    self.s.cookies.update(self.get_cookies()[0])

    # self.s.headers.update({"Cookies": self.get_cookies()})

  def get_cookies(self):
    """
    获取上一次请求的cookie
    :return: 返回cookie dict
    """
    r = self.s.get(self.url)
    rint(r.cookies.get_dict())
    return (r.cookies.get_dict(), r.text)

  def get_token(self):
    ""
    获取上一次请求隐匿的表单token
    :return:
    """
    pattern = ‘name="__RequestVerificationToken" type="hidden" value="(.*)"‘
    p = re.compile(pattern)
    text = self.get_cookies()[1]
    if p.search(text):
      token = p.search(text).groups()[0]
      token = token.__str__().strip(‘"‘)
    else:
      return
    eturn token

  def get_mobile(self):
    s = "144"
    n = range(10)
    for i in range(8):
    s += random.choice(n).__str__()
    if len(s) == 4 and s == "1442":
    s = (int(s) - 1).__str__()
    print(s)
    return s

  def regist(self):
    param = {"__RequestVerificationToken": self.get_token(),
    "MobilePhone": self.get_mobile(),
    "PassWord": "123456a",
    "ConfirmPassword": "123456a",
    "IntroducerMobile": "",
    "IsAcceptPact": "true"}
    r = self.s.post(self.url, data=param)
    try:
      eturn json.loads(r.text)
    except:
      return r.text


if __name__ == ‘__main__‘:
print(Regist().regist())

requests 获取token

标签:ati   content   upd   rand   cookies   type   phone   ret   for   

原文地址:https://www.cnblogs.com/tnyleyon/p/9505063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!