request模拟知乎登录实例代码


本文摘自php中文网,作者零下一度,侵删。

import request

try:

  import cookielib  #python2版本

except:

  import http.cookiejar as cookielib  #python3版本

import re

import

session=request.session()

session.cookies=cookielib.LWPCookieJar(filename="cookies.txt")  #将cookies存储到本地文件

#加载cookies文件

try:

  session.cookies.load(ignore_discard=True)

except:

  print("cookies未能加载")

User_Agent="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"

header={

  "HOST"  :  "www.zhihu.com",

  "Referer"  :  "https://www.zhihu.com",

  "User_Agent"  :  User_Agen"

}

#获取xsrf

def get_xsrf():

  response=session.post("https://www.zhihu.com",headers=header)  #请求网页需带上头文件

  match_obj=re.match(' .*name="_xsrf" value="(.*?)" ')  #注意使用单双引号

  if match_obj:

    return (match_obj(1))

  else:

    return " "

def get_index():

  response=session.get("https://www.zhihu.com",headers=header)

  with open("index_page.heml",wb) as f:

    f,write(response.text.encode("utf-8"))

  print ("ok")

#模拟知乎登录

def zhihu_login(account,password):

  if re.match("^1\d{10}",account):  #验证账号是否为手机号

    print ("手机登录")

    post_url="https://www.zhihu.com/login/phone_num"

    post_data={

      "_xsrf"  :  get_xsrf(),

      "phone_num"  :  account,

      "password"  :  password

    }

  else:

    if "@" in account:

      print (“邮箱登录”)

      post_url="https://www.zhihu.com/login/email"

      post_data={

      "_xsrf"  :  get_xsrf(),

      "email"  :  account,

      "password"  :  password

    }

  response_text=session.post(post_url,post_data,headers=header)

  session.cookies.save()

#验证是否登录成功

def is_login():

  inbox_url="https://www.zhihu.com/inbox"

  response=session.get(inbox_url,headers=header,allow_redirects=False)

  if response.status_code !=200:

    return False

  else:

    return True

zhihu.login("18782902568","admin123")

get_index()

以上就是request模拟知乎登录实例代码的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

win8怎么安装Python

Python中调用外部命令是什么

Python笔试题之设计“跳一跳”小游戏计分器

Python爬虫基础之网页组成解析

Python和spyder的区别

怎么用Python打开文件

如何将字符串转成字典

Python如何实现数字炸弹游戏

Python面向对象编程的详细介绍

Python怎么找外包

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...