代码部分
import requests
# 设置 Cookie 和目标 URL学习通-字典方式传递cookie.py
cookies = {
# 将从浏览器获取的 Cookie 粘贴到此处
'Cookie': 'fid=16240; lv=1; xxtenc=590688748c59a9cf32d077a1852b302a; _uid=205386953; UID=205386953; vc=7D6178B66A49A6CB33F821E6E6646B58; uf=b2d2c93beefa90dc09eff9330055068b5b948519e3a7d6ada3a9f32e18340186a67051ee2d61ce43640d23e1111dd22430d92481d752d66f88b83130e7eb47045ac8670337949add52fbddc3b2f63c9f3ad59b143144275b91dceb18fd7c9bf3e52d0ec49fdf9329; _d=1736931383254; vc2=B8A98E7A7D83753E36A9A681A323ABD0; vc3=HWGEfofL6RDJVBEIcick%2Fsgy7%2FyvDzcqd89Mes6kilODY13vdqcBWWZh%2Bpv9Ase9TkYbxufCjN9%2F5aaK59jFt2KppF%2FFZUb5Tj0KlttJ6t7aFz7gd0c%2BDdVnCFI%2FNAjMYZtG51bbKJ4cic5IcERWyKyuhhg2CRwnJfWjbiNeihA%3D7473d2cbf3892d3ef0ad34bd20ec0deb; cx_p_token=af599aebfd327529886ea6989d7e000e; p_auth_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIyMDUzODY5NTMiLCJsb2dpblRpbWUiOjE3MzY5MzEzODMyNTYsImV4cCI6MTczNzUzNjE4M30.x_8287TyuORHH5xNHPdpbnErHkmiAEVJebcTxh2aObk; DSSTASH_LOG=C_38-UN_136-US_205386953-T_1736931383256; tl=1; jrose=95BEF312B658D03ACB8F0813559B67C9.ans; source=""; spaceFidEnc=F9CFDF973F99C43D5D06B763BFFEE1FB; spaceFid=16240; spaceRoleId=3',
}
url = "https://i.chaoxing.com/" # 学习通首页 URL
# 设置请求头(模拟浏览器)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0 Safari/537.36',
}
#创建一个session对象
session=requests.session()
# 发起请求
response = session.get(url, headers=headers, cookies=cookies)
# 检查响应状态码
if response.status_code == 200:
print("成功获取数据!")
print(response.text) # 打印首页 HTML 内容
else:
print(f"请求失败,状态码: {response.status_code}")
#获取cookie信息
#方式二【session对象自动保存了上次的cookie值,相当于模拟了浏览器记录cookie的行为,下次请求时直接使用即可】
# 发起请求
response = session.get(url, headers=headers)
# 检查响应状态码
if response.status_code == 200:
print("利用session对象自动传递cookie,重新成功获取数据!") #失败 #原因:返回到了登录页面
print(response.text) # 打印首页 HTML 内容
else:
print(f"请求失败,状态码: {response.status_code}")