Python 3.5

# -*- coding: utf-8 -*-
"""
Created on Wed May 3 16:26:55 2017 @author: x-power
""" import requests
import http.cookiejar as cookielib
import re
import time
import os.path
from PIL import Image # 构造 Request headers
headers = {
"Host": "www.zhihu.com",
"Referer": "https://www.zhihu.com/",
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0',
} # 构造 cookie 信息
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies')
try:
session.cookies.load(ignore_discard=True) # 如果已经有 cookie信息的话 直接用于登录
except:
print("Cookie 未能加载") # 以后再用session 访问的时候 都带着 本地已经固定的cookie信息,代表都是一台机器发出的请求。 def get_xsrf():
'''_xsrf 是一个动态变化的参数'''
index_url = 'https://www.zhihu.com'
# 获取登录时需要用到的_xsrf
index_page = session.get(index_url, headers=headers)
html = index_page.text
pattern = r'name="_xsrf" value="(.*?)"'
# 这里的_xsrf 返回的是一个list
_xsrf = re.findall(pattern, html)
return _xsrf[0] # 获取验证码
def get_captcha():
t = str(int(time.time() * 1000))
captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + "&type=login"
r = session.get(captcha_url, headers=headers)
with open('captcha.jpg', 'wb') as f:
f.write(r.content)
f.close()
# 用pillow 的 Image 显示验证码
# 如果没有安装 pillow 到源代码所在的目录去找到验证码然后手动输入
try:
im = Image.open('captcha.jpg')
im.show()
im.close()
except:
print(u'请到 %s 目录找到captcha.jpg 手动输入' % os.path.abspath('captcha.jpg'))
captcha = input("please input the captcha\n>")
return captcha def isLogin():
# 通过查看用户个人信息来判断是否已经登录
url = "https://www.zhihu.com/settings/profile"
login_code = session.get(url, headers=headers, allow_redirects=False).status_code #allow_redirects 不允许重定向
if login_code == 200:
return True
else:
return False def login(secret, account):
_xsrf = get_xsrf()
headers["X-Xsrftoken"] = _xsrf
headers["X-Requested-With"] = "XMLHttpRequest"
# 通过输入的用户名判断是否是手机号
if re.match(r"^1\d{10}$", account):
print("手机号登录 \n")
post_url = 'https://www.zhihu.com/login/phone_num'
postdata = {
'_xsrf': _xsrf,
'password': secret,
'phone_num': account
}
else:
if "@" in account:
print("邮箱登录 \n")
else:
print("你的账号输入有问题,请重新登录")
return 0
post_url = 'https://www.zhihu.com/login/email'
postdata = {
'_xsrf': _xsrf,
'password': secret,
'email': account
}
# 不需要验证码直接登录成功
login_page = session.post(post_url, data=postdata, headers=headers)
login_code = login_page.json()
if login_code['r'] == 1:
# 不输入验证码登录失败
# 使用需要输入验证码的方式登录
postdata["captcha"] = get_captcha()
login_page = session.post(post_url, data=postdata, headers=headers)
login_code = login_page.json()
print(login_code['msg'])
# 保存 cookies 到文件,
# 下次可以使用 cookie 直接登录,不需要输入账号和密码
session.cookies.save() if __name__ == '__main__':
if isLogin():
print('您已经登录')
else:
account = input('请输入你的用户名\n> ')
secret = input("请输入你的密码\n> ")
login(secret, account)

知乎模拟登录 requests session的更多相关文章

  1. 知乎模拟登录,支持验证码和保存 Cookies

    import requests import time import re import base64 import hmac import hashlib import json import ma ...

  2. Java爬虫——模拟登录知乎

    登录界面,首先随意输入一个账号,登录查看发送表单的请求 可以发现请求是Post : https://www.zhihu.com/login/phone_num 发送的表单是 _xsrf: passwo ...

  3. 在Python中用Request库模拟登录(一):字幕库(无加密,无验证码)

    字幕库的登录表单如下所示,其中省去了无关紧要的内容: <form class="login-form" action="/User/login.html" ...

  4. Python3 模拟登录知乎(requests)

    # -*- coding: utf-8 -*- """ 知乎登录分为两种登录 一是手机登录 API : https://www.zhihu.com/login/phone ...

  5. 【爬虫】python requests模拟登录知乎

    需求:模拟登录知乎,因为知乎首页需要登录才可以查看,所以想爬知乎上的内容首先需要登录,那么问题来了,怎么用python进行模拟登录以及会遇到哪些问题? 前期准备: 环境:ubuntu,python2. ...

  6. 【Python数据分析】Python模拟登录(一) requests.Session应用

    最近由于某些原因,需要用到Python模拟登录网站,但是以前对这块并不了解,而且目标网站的登录方法较为复杂, 所以一下卡在这里了,于是我决定从简单的模拟开始,逐渐深入地研究下这块. 注:本文仅为交流学 ...

  7. 4 使用Selenium模拟登录csdn,取出cookie信息,再用requests.session访问个人中心(保持登录状态)

    代码: # -*- coding: utf-8 -*- """ Created on Fri Jul 13 16:13:52 2018 @author: a " ...

  8. Python爬虫 —— 知乎之selenium模拟登陆获取cookies+requests.Session()访问+session序列化

    代码如下: # coding:utf-8 from selenium import webdriver import requests import sys import time from lxml ...

  9. Python爬虫初学(三)—— 模拟登录知乎

    模拟登录知乎 这几天在研究模拟登录, 以知乎 - 与世界分享你的知识.经验和见解为例.实现过程遇到不少疑问,借鉴了知乎xchaoinfo的代码,万分感激! 知乎登录分为邮箱登录和手机登录两种方式,通过 ...

随机推荐

  1. 李洪强iOS开发之-实现点击单行View显示和隐藏Cell

    李洪强iOS开发之-实现点击单行View显示和隐藏Cell 实现的效果:  .... ....

  2. Array types are now written with the brackets around the element type问题的解决方法

    在xcode6.1中来编写swift空数组时.出现的的这个问题,依照官方 Swift 教程<The Swift Programming Language>来写 let emptyArray ...

  3. 查询历史使用过的命令并使用(history)

    一.什么是history 在bash功能中.它能记忆使用过的命令,这个功能最大的优点就是能够查询以前做过的举动.从而能够知道你的执行步骤.那么就能够追踪你曾下达过的命令.以作为除错的工具. 二.His ...

  4. 理解和使用WPF 验证机制

    博客 学院 下载 更多 写博客 发布Chat 登录注册 理解和使用WPF 验证机制 原创 2013年06月20日 11:15:37 7404 首先建立一个demo用以学习和实验WPF Data Val ...

  5. ViewFlow增强onItemClick功能及ViewFlow AbsListView源代码分析

    先看实现效果,上图:  ViewFlow是一个非常好用的,用于不确定item个数的水平滑动切换的开源项目. 可是从github上下载的ViewFlow事实上是不支持onItemClick功能的,tou ...

  6. 组合式+迭代式+链式 MapReduce

    1.迭代式mapreduce 一些复杂的任务难以用一次mapreduce处理完成,需要多次mapreduce才能完成任务,例如Pagrank,Kmeans算法都需要多次的迭代,关于mapreduce迭 ...

  7. locate和grep命令

    这任然是一篇读书笔记,以下内容来源<linux命令速查手册>这本书. 1.locate命令 用文件名或者文件名的部分来搜索文件在系统中的位置.locate不搜索具体目录,而是搜索一个数据库 ...

  8. I2S总线协议理解

    I2S总线 Inter IC Sound总线又称集成电路内置音频总线. I2S对数字音频设备之间的音频数据传输而制定的一种总线标准. 采用了沿独立的导线传输时钟与数据信号的设计,通过将数据和时钟信号分 ...

  9. react项目中的注意点

    一.ES6 的编译方法 目前主流的浏览器还不支持ES6. 现在一般采用webpack 和 <script type="text/babel">对jsx  语法进行编译, ...

  10. mpvue——实现点击数组内的某一元素进行置顶(排序第一)操作

    前言 其实很简单只是用了js的几个函数 substr unshift splice 完整代码 | mpvue模仿QQ 代码 思路很简单,获取当前元素下标然后通过unshift函数将该值插入到数组第一位 ...