【python爬虫学习】cookie模拟登陆

近期学校要求登陆一个网站学习,要计算在线时长,长时间不对这个页面进行操作的话就会停止计时。就想着能不能写个程序模拟登陆并进行一些操作。

模拟登陆的话有很多方法,因为有验证码比较麻烦,所以我是自己先登陆一下,抓取cookie给程序用。

首先F12,再登陆一下网站,选择Network,看到下图

【python爬虫学习】cookie模拟登陆_第1张图片

可以看到在Request Headers中有cookie字段,把它复制下来。

下面开始写爬虫

from fake_useragent import UserAgent
import requests

ua = UserAgent(path= r'C:\Users\****\AppData\Local\Temp\fake_useragent.json')

school_s = requests.session()
headers_school= {'User-Agent': ua.chrome,'Cookie':'ASP.NET_SessionId=gz5eg2r2n0ec0ycqhr51****'}
r = school_s.get('http://ystu.****.edu.cn/default.aspx',headers= headers_school)
r.encoding = r.apparent_encoding
print(r.text)

输出

【python爬虫学习】cookie模拟登陆_第2张图片

可以看到,程序已经登陆成功了。学校的网站一般都比较容易爬些,有些安全性高的网站就没这么容易了

你可能感兴趣的:(爬虫)