用不同的库实现模拟登陆知乎!
程序员文章站
2024-03-17 21:52:52
...
对应目标网站: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)
结果也同样是和第一种方法一样,是不是代码更简洁了呢!!
上一篇: c++ 二分查找&sort函数的学习
下一篇: 改版知乎模拟登陆