通過cookie登錄以及使用賬號密碼登錄

cookie就是讓服務器知道是同一個人
即辨別身份的

比如你先登錄進入到CSDN中
然後複製鏈接重新打開
會提示你沒有登錄
另一種解釋就是帶着賬戶和密碼連接服務器

瀏覽器的開發者選項中可以看懂cookie

下面的cookie內容是從登錄後瀏覽器中複製的
如果不加cookie會提示無法登錄
因爲你之前沒有登陸過
加了之後就可以登陸了

////////////////////////////////

from urllib.request import Request, urlopen
from fake_useragent import UserAgent

url = "http://www.sxt.cn/index/user.html"
headers = {
    "User-Agent": UserAgent().chrome,
    "Cookie": "UM_distinctid=163d8c88a6740c-01c2fe892f8d8c-737356c-100200-163d8c88a682a2; 53gid2=10466932807008; 53revisit=1528350416275; 53gid1=10466932807008; acw_tc=AQAAAIktZUa8ZQEAoCEsceTKxzX+LOad; CNZZDATA1261969808=52059414-1528348034-%7C1532407588; PHPSESSID=uh265s5725vojpqdsbagj0n726; visitor_type=old; 53gid0=10466932807008; 53kf_72085067_from_host=www.sxt.cn; 53kf_72085067_keyword=http%3A%2F%2Fwww.sxt.cn%2Findex%2Flogin%2Flogin.html; 53kf_72085067_land_page=http%253A%252F%252Fwww.sxt.cn%252F; kf_72085067_land_page_ok=1"
}
request = Request(url, headers=headers)
response = urlopen(request)

print(response.read().decode())

////////////////////////////////////////////////////////////////

以上是建立在已經登錄過的二次登錄
現在我們直接登錄
這裏我用的是CSDN
文件名是dologin
你打開後看右邊就會有賬號密碼

from urllib.request import Request, urlopen
from fake_useragent import UserAgent
from urllib.parse import urlencode
from urllib.request import HTTPCookieProcessor,build_opener
# 登錄
#這個URL通過F12network的ALL
# 別忘了勾選Preserve log
#中文意思保留請求日誌
#你很好奇爲什麼有2個request和response
#因爲第一個是你爲了登錄
#第二個是登陸後顯示的
#沒有第一個就沒有第二個
login_url = "https://passport.csdn.net/v1/register/pc/login/doLogin"
headers = {
    "User-Agent": UserAgent().chrome,
}
form_data = {
    "user": "13509142891",
    "password": "2603zawxr123"
}
# 把數據進行編碼
f_data = urlencode(form_data).encode()
request = Request(login_url, headers=headers, data=f_data)
#response = urlopen(request) 錯誤的
handler = HTTPCookieProcessor()
opener = build_opener(handler)
#很有可能代碼在此處出錯
response = opener.open(request)
# 訪問頁面
info_url = "https://blog.csdn.net/qq_43776408"
request = Request(info_url, headers=headers)
response = opener.open(request)
print(response.read().decode())

#第二種代碼出錯
#老師使用的是http網站
#我使用的是https網站
#可能要使用http網站
#代碼本身沒有錯
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章