zoukankan      html  css  js  c++  java
  • Python模拟登录实战(三)

    目标:模拟登录知乎

    代码如下:

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 __author__ = 'ziv·chan'
     4 
     5 
     6 import re
     7 import time
     8 import requests
     9 from PIL import Image
    10 
    11 
    12 url_login = 'https://www.zhihu.com/login/phone_num'
    13 
    14 headers = {
    15         'Host' : 'www.zhihu.com',
    16         'Origin' : 'https://www.zhihu.com',
    17         'Referer' : 'https://www.zhihu.com/',
    18         'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'
    19 }
    20 
    21 session = requests.session()
    22 
    23 # 获取xsrf
    24 def get_xsrf():
    25     url = 'https://www.zhihu.com/#signin'
    26     html = session.get(url)
    27     pageCode = html.text
    28     pattern = re.compile('name="_xsrf" value="(.*?)"/>',re.S)
    29     xsrf = re.search(pattern,pageCode).group(1)
    30     return xsrf
    31 
    32 # 获取验证码
    33 def get_captcha():
    34     # 获取验证码url
    35     t = str(int(time.time() * 1000))
    36     url = 'http://www.zhihu.com/captcha.gif?r=%s&type=login' % t
    37     cha = session.get(url)
    38     with open('cha.jpg', 'wb') as f:
    39         f.write(cha.content)
    40         f.close()
    41         im = Image.open('cha.jpg')
    42         im.show()
    43         im.close()
    44     captcha = raw_input("请输入验证码")
    45     return captcha
    46 
    47 
    48 form_data = {
    49         '_xsrf' : get_xsrf(),
    50         'password' : 'ChelseaFC.1',
    51         'captcha' : get_captcha(),
    52         'remember_me' : 'true',
    53         'phone_num' : '18362972928'
    54 }
    55 print form_data
    56 # 注意用法
    57 res = session.post(url_login,data=form_data,headers=headers)
    58 print res.json()['msg']

    输出:

    请输入验证码edx5
    {'phone_num': '18362972928', '_xsrf': u'83488f00833e19acc086395dbce597c4', 'password': 'ChelseaFC.1', 'remember_me': 'true', 'captcha': 'edx5'}
    登陆成功

    难点:验证码的URL中的参数‘r’取自当前时间的时间戳(1970纪元后经过的浮点秒数)再处理

    以上。

  • 相关阅读:
    node中一个基本的HTTP客户端向本地的HTTP服务器发送数据
    HTTP客户端之使用request方法向其他网站请求数据
    node的close
    node的超时timeout
    node中的ajax提交小例子
    node中转换URL字符串与查询字符串
    node.js 获取客户端信息
    用SCMD2.0.8.0汉化版制作OB地图简易教程
    js 调用 android 安卓 代码
    项目需要简单些了个WEB APP 的弹出窗
  • 原文地址:https://www.cnblogs.com/ziv-chan/p/5508283.html
Copyright © 2011-2022 走看看