1. 程式人生 > >Python3 使用cookiejar管理cookie

Python3 使用cookiejar管理cookie

這次我們使用cookiejar來完成一個登入學校model平臺,並檢視登陸後的其他頁面的任務

from urllib import request
from urllib import parse
from http import cookiejar

if __name__ == '__main__':
    # 建立cookie管理
    cookie_jar = cookiejar.CookieJar()
    handler = request.HTTPCookieProcessor(cookie_jar)
    opener = request.build_opener(handler)
    # 建立post訪問request
url = 'http://moodle.zwu.edu.cn/login/index.php' data = { 'username': '填寫學號', 'password': '填寫密碼' } headers = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } post_data = parse.urlencode(data).encode('utf-8') request = request.Request(url, post_data, headers) # 訪問
html = opener.open(request).read().decode('utf-8') print(html)