python爬蟲之模擬登錄將cookie保存到代碼中


#!/usr/local/bin/python3.7

"""
@File    :   cookiejar_login.py
@Time    :   2020/04/05
@Author  :   Mozili

"""

import urllib.request
import urllib.parse
# cookiejar用來保存cookie
import http.cookiejar

# 創建一個cookiejar對象
cj = http.cookiejar.CookieJar()
# 創建一個haddler對象
haddler = urllib.request.HTTPCookieProcessor(cj)
# 創建一個opener對象
opener = urllib.request.build_opener(haddler)

# post請求url
post_url = 'http://team.speedtest.cn/login'
# post請求參數
data = {
    'account':'mozili',
    'password':'xxx'
}
# 創建請求頭部
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15'
}
# 對參數進行處理
data = urllib.parse.urlencode(data).encode()
# 創建一個request
request = urllib.request.Request(url=post_url, headers=headers)
# 發送請求,注意使用opener
response = opener.open(request, data=data)
# 打印請求結果
print(response.read().decode())
print('------我是分界線-------')

# 登錄成功后,進行get請求
get_url = 'http://team.speedtest.cn/?type=my'
request = urllib.request.Request(url=get_url, headers=headers)
response = opener.open(request)
print(response.read().decode())

 

說明:

1、post請求url、請求數據以及請求頭都痛過抓包工具獲得(get請求也一樣),如下圖

(1)獲取請求url

 

 

(2)獲取data

 

 

(3)獲取headers

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM