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. C#语言循环语句for嵌套

  2. leetcode第一刷_Best Time to Buy and Sell Stock III

    这道题还是挺难的,属于我前面提到的,给个数组,线性时间找出个什么东西,尽管上面的两个买卖股票也是这类.只是相比之下稚嫩多了.有关至少至多的问题比較烦人,不好想,等再做一些题,可能会发现什么规律.这道题 ...

  3. 下载Google官方/CM Android源码自己主动又一次開始的Shell脚本

    国内因为某种原因,下载CM或Google官方的Android源码总easy中断.总看着机器.一中断就又一次运行repo sync还太麻烦,所以我特意编写了一段shell脚本(download.sh). ...

  4. 【bzoj3210】花神的浇花集会

    将(x,y)转化成(x+y,x-y)可以将切比雪夫距离转化成曼哈顿距离(自己推一推) A.B的切比雪夫距离就是A‘.B‘曼哈顿距离的一半. 那么可以将x.y分离处理,排序中位数即可. 注意如果最后选的 ...

  5. all rows from client_id can grow infinitely compared to a single node when hashing by client_id

    all rows from client_id can grow infinitely compared to a single node when hashing by client_id Re: ...

  6. HDU2255 奔小康赚大钱 【模板】 二分图完美匹配

    基本概念 二分图有两个种点:X和Y.X与Y之间存在一些边,每个边有一个权值.现要求求一组X与Y间的通过边实现的一一匹配,使得得到的边权和最大. 总体过程 对每个X节点设置一个顶标Xl,初值为与X相邻的 ...

  7. elasticsearch索引查询,日志搜素

    索引查询 http://10.199.137.115:9200/_cat/indices?format=json 返回json字符串的索引状态 增加索引名称过滤 http://10.199.137.1 ...

  8. regmap使用介绍【转】

    本文转载自:http://blog.csdn.net/hellowxwworld/article/details/10737569 内核3.1引入一套新的API regmap,目的是提取出关于I2C ...

  9. Web Assembly背景

    Javascript ,也叫Ecma script,  是这家伙用了 10 天时间赶出来的.. 所以,各位程序猿们,如果你觉得老板 10 天要你们上线一个 App 是一个丧心病狂的事情,那么可以多想想 ...

  10. sublime text3 3176激活

    更改hosts sudo vim /etc/hosts 127.0.0.1 www.sublimetext.com 127.0.0.1 license.sublimehq.com 输入激活码 ---- ...