1. 程式人生 > >urllib庫利用cookie實現模擬登入慕課網

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)


執行結果

入下圖,可以看到,已經可以獲取到登入後的一些資訊了