urllib库利用cookie实现模拟登录慕课网

思路

1.首先在网页中使用账户和密码名登录慕课网

2.其次再分析请求头,如下图所示,获取到请求URL,并提取出cookie信息,保存到本地

3.最后在代码中构造请求头,使用urllib.request发送包含cookie信息的请求

源码

# !/usr/bin/env python
# -*- coding:utf-8 -*-

"""
使用Cokie模拟登录
"""

import urllib.request

url="http://www.imooc.com/u/2346025"
cookie="自己的Cookie字符串"
request_header={
    "Accept":"image/webp,image/apng,image/*,*/*;q=0.8",
    # Accept-Encoding:gzip, deflate, br
    "Accept-Language":"zh-CN,zh;q=0.9",
    "Connection":"keep-alive",
    "Cookie":cookie,
    # Host:hm.baidu.com",
    # "Referer":"http://www.imooc.com/u/2346025",
    "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36"
}

req=urllib.request.Request(url,headers=request_header)

resp=urllib.request.urlopen(req)

data=resp.read().decode('utf-8')

print(data)

  

运行结果

入下图,可以看到,已经可以获取到登录后的一些信息了

网址:http://blog.csdn.net/topleeyap/article/details/78841383

其它:

Python爬虫之模拟登录总结:http://blog.csdn.net/churximi/article/details/50917322

Python 模拟登录知乎:http://blog.csdn.net/Marksinoberg/article/details/69569353

Python 网络爬虫--简单的模拟登录:http://blog.csdn.net/M_WBCG/article/details/70243372

原文地址:https://www.cnblogs.com/cxscode/p/8260469.html