用不同的庫實現模擬登陸知乎!

不掉髮的王然然發表於2020-10-22

對應目標網站:https://www.zhihu.com/hot

首先當然是開啟我們的知乎官網,然後登陸以後如下圖所示:

在這裡插入圖片描述

按下F12,點選Network項,找到對應的hot開啟,找到cookie項,複製一下。如下圖所示:

在這裡插入圖片描述

我們先來用第一種方法用urllib庫實現知乎的模擬登陸

from urllib import request

url='https://www.zhihu.com/hot'
headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    'cookie': '_zap=05b80470-e821-4a9f-9c61-809813eb7d16; d_c0="ANCZmXnpCxKPTt573oe2SdyIyPmYiX7UwyE=|1602817046"; _xsrf=zRCIgDyxrJLAczq8WtK1xGuNxIpwB6Eo; tshl=; capsion_ticket="2|1:0|10:1603181959|14:capsion_ticket|44:Y2I2MTZhNWMwMWU2NDc5NWI5MjQyNDFkOTIxYTFiYzU=|efce3db52d1d73a1c51c9b689074bf26d809ed9a6766b6dec28b765852077bff"; z_c0="2|1:0|10:1603181960|4:z_c0|92:Mi4xSEpBS0hBQUFBQUFBMEptWmVla0xFaVlBQUFCZ0FsVk5pT3Q3WUFCS3FER05rQWtKWVVGWmVnYjFYWVdTT0NCZERR|21a1c9396569861bf6f957c8a2384368463bed7d4efcbc780376beffc29c089a"; q_c1=9bf5eed58fc74b2eac63e874fff06738|1603182065000|1603182065000; tst=h; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1602817104,1603180750,1603328979; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1603328979; SESSIONID=jd2BQaplPUbm511MeDJf1nH6xU5j09Q2qmhkr4UsbET; JOID=W1AUAkoZiYM2nkN7LRHAUu8Xonk3cuSxdMcjAkFB3ehbq3pLaeRbE2GXS3ItylStJxi2FW9atwrYypQ9kp6zT8E=; osd=UFATC0oSiYQ_nkh7KhjAWe8Qq3k8cuO4dMwjBUhB1uhconpAaeNSE2qXTHstwVSqLhi9FWhTtwHYzZ09mZ60RsE=; KLBRSID=fe0fceb358d671fa6cc33898c8c48b48|1603329020|1603329009'}
rq=request.Request(url,headers=headers)
resp=request.urlopen(rq)
print(resp.read().decode('utf-8'))

結果和知乎熱榜上的內容是一致的!
在這裡插入圖片描述
僅此方法實在是太簡單了!!!
然後我們再用第二種方法也就是resuests庫來實現模擬登陸!
因為開始的步驟是一致的需要登入,然後我們直接上程式碼

import requests
url='https://www.zhihu.com/hot'
headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    'cookie': '_zap=05b80470-e821-4a9f-9c61-809813eb7d16; d_c0="ANCZmXnpCxKPTt573oe2SdyIyPmYiX7UwyE=|1602817046"; _xsrf=zRCIgDyxrJLAczq8WtK1xGuNxIpwB6Eo; tshl=; capsion_ticket="2|1:0|10:1603181959|14:capsion_ticket|44:Y2I2MTZhNWMwMWU2NDc5NWI5MjQyNDFkOTIxYTFiYzU=|efce3db52d1d73a1c51c9b689074bf26d809ed9a6766b6dec28b765852077bff"; z_c0="2|1:0|10:1603181960|4:z_c0|92:Mi4xSEpBS0hBQUFBQUFBMEptWmVla0xFaVlBQUFCZ0FsVk5pT3Q3WUFCS3FER05rQWtKWVVGWmVnYjFYWVdTT0NCZERR|21a1c9396569861bf6f957c8a2384368463bed7d4efcbc780376beffc29c089a"; q_c1=9bf5eed58fc74b2eac63e874fff06738|1603182065000|1603182065000; tst=h; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1602817104,1603180750,1603328979; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1603328979; SESSIONID=jd2BQaplPUbm511MeDJf1nH6xU5j09Q2qmhkr4UsbET; JOID=W1AUAkoZiYM2nkN7LRHAUu8Xonk3cuSxdMcjAkFB3ehbq3pLaeRbE2GXS3ItylStJxi2FW9atwrYypQ9kp6zT8E=; osd=UFATC0oSiYQ_nkh7KhjAWe8Qq3k8cuO4dMwjBUhB1uhconpAaeNSE2qXTHstwVSqLhi9FWhTtwHYzZ09mZ60RsE=; KLBRSID=fe0fceb358d671fa6cc33898c8c48b48|1603329020|1603329009'}
resp=requests.get(url,headers=headers)
print(resp.text)

結果也同樣是和第一種方法一樣,是不是程式碼更簡潔了呢!!

相關文章