使用Python模拟登录知乎


之前用Scrapy把 伯乐在线上的所有的文章爬取下来,还准备把相亲板块爬取下来。不过伯乐在线不用登录就可以爬取信息,也没什么意思,所以就选择试着用Python模拟登录知乎。

环境和开发工具

  • Python3.6+macOS
  • Firefox

模拟登录的过程

  • 使用浏览器查看客户端和服务器间的通讯

  • 查看发送请求时需要传送的参数

  • 使用Python构造一组参数向服务器发起请求

    需要注意的问题

    • 需要向哪个URL发起请求
    • 需要传送哪些参数
    • 如何使用session和cookie保持登录的状态
    • 当需要输入验证码的时候怎么操作

查看参数

首先打开知乎的首页 https://www.zhihu.com

登录

直观上看,需要输入一个账号和一个密码,具体向哪个url发起请求暂时无法查看,不过我们可以试一下输入一个错误的账号密码,然后通过查看客户端和服务器端的通信来查看一些参数。

查看需要发起请求的URL
参数

通过Firefox查看到了一些必须的参数,比如_xsrf、password、phone_num,captcha_type(后来发现把cn去掉验证码更简单。),似乎只需要将这些数据POST到/login/phone_num就能实现登录。
使用email模拟登陆操作和上面是一样的。
这几个参数中,_xsrf看上去稍微特殊一点

CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。尽管听起来像跨站脚本(XSS),但它与XSS非常不同,XSS利用站点内的信任用户,而CSRF则通过伪装来自受信任用户的请求来利用受信任的网站。

通过在网页上查询,发现了这个参数,只有将这个随机产生参数放在POST中才能将请求发送到目标URL


代码实现

在这个模拟登录的过程中,主要是用到requests来进行请求,然后记录下信息到cookie中方便以后不用输入账号密码登录。

import requests
#python2中是cookielib,Python3中是http下的cookiejar
try:
    import cookilelib
except:
    import http.cookiejar as cookielib
# 使用登录cookie信息
session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies.txt')
try:
    session.cookies.load(ignore_discard=True)
except:
    print("Cookie 未能加载")

第一步是设置好请求的headers

headers = {
    "HOST":"www.zhihu.com",
    "Referer":"https://www.zhihu.com",
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:55.0) Gecko/20100101 Firefox/55.0"
}

通过上面的参数查看,其中账号密码由自己输入,_xsrf在网页代码中用正则表达式或者用scrapy的选择器找到:

import re
# 获得_xsrf
def get_xsrf():
    response=session.get("https://www.zhihu.com",headers=headers)
    match_obj= re.match('.*name="_xsrf" value="(.*?)"',response.text,re.S)

    if match_obj:
        return match_obj.group(1)
    else:
        return ""

将我们在网页中看到的需要的参数POST到目标URL中就可以模拟登录了

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 = session.post(post_url, data=post_data, headers=headers)
     #将登录的信息进行保存
    session.cookies.save()   

不过这么登录的时候会返回一些错误,比如:“验证码会话无效 :(”。说明模拟登录时还是需要输入验证码的

from PIL import Image
# 获取验证码
def get_captcha():
    #本来觉得可能需要加上时间的参数,不过不需要时间也是可以获得验证码
    # t = str(int(time.time() * 1000))
    # captcha_url = "https://www.zhihu.com/captcha.gif?r=%s&type=login"%t
    captcha_url = "https://www.zhihu.com/captcha.gif?&type=login"
    captcha_image = session.get(captcha_url, headers=headers)
    with open('captcha.gif', 'wb') as f:
        f.write(captcha_image.content)
        f.close()
    try:
        im=Image.open("captcha.gif")
        im.show()
        captcha = input("please input the captcha:")
        im.close()
        return captcha
    except:
        print("未打开验证码文件")

对之请求返回的信息进行处理,判断是否需要输入验证码

import json
#将修改captcha这个参数加到post_data中
def zhihu_login(account, password):
         ...
login_msg = json.loads(response.text)
    #判断是否需要输入验证码
    if login_msg["r"]==1:
        post_data["captcha"]=get_captcha()
        response = session.post(post_url,data=post_data,headers=headers)
        print(json.loads(response.text)["msg"])

由于我们存储了登录的cookie,如果之前有登录成功过就可以直接登录

def isLogin():
    # 通过查看用户个人信息来判断是否已经登录
    url = "https://www.zhihu.com/settings/profile"
    login_code = session.get(url, headers=headers, allow_redirects=False).status_code
    if login_code == 200:
        return True
    else:
        return False

最后就是运行了:

if __name__ == '__main__':
    if isLogin():
        print('您已经登录')
    else:
        account = input("请输入你的用户名\n--->  ")
        password = input("请输入你的密码\n--->  ")
        zhihu_login(account, password)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容