session会话对象
作用:
1.可以进行请求的发送
2.如果请求过程中产生了cookie,则该cookie会被自动存储/携带在该session对象中
使用:
创建一个session对象:
session=requests.Session()
使用session对象进行模拟登录请求的发送,登录成功后cookie就会被存储到session中
再次进行请求发送,第二次请求会携带cookie
代码示例
# 模拟登录红薯网
import requests
from lxml import etree
from demo.demo3.chaojiying import Chaojiying_Client
if __name__ == '__main__':
url="https://i.hongshu.com/login.html"
headers = {
"User-Agent": "Mozilla/5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 88.0.4324.150 Safari / 537.36"
}
resp=requests.get(url=url,headers=headers)
resp.encoding="utf-8"
page_text=resp.text
tree=etree.HTML(page_text)
img_src=tree.xpath("//img[@id='imgValidCode']/@src")[0]
img_data=requests.get(url=img_src,headers=headers).content
with open("./img.jpg","wb") as fp:
fp.write(img_data)
# 超级鹰用户名
username="1056333479"
# 超级鹰密码
password="zhengyunyu524"
# 软件id
id="912891"
chaojiying = Chaojiying_Client(username, password, id) # 用户中心>>软件ID 生成一个替换 96001
im = open('./img.jpg', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
img_str=chaojiying.PostPic(im, 1902)['pic_str']
print(img_str)
# 模拟登录
data={
"username":"1056333479",
"password":"zhengyunyu524",
"validcode":img_str,
"url":"",
"sign":"",
"logining":"1"
}
# 创建session对象
session=requests.Session()
# 登录后将cookie存储到session域中
login_resp=session.post(url=url,data=data,headers=headers)
if(login_resp.status_code==200):
print("登录成功")
user_url="https://i.hongshu.com/profile/center.do"
user_resp=session.get(url=user_url,headers=headers)
user_resp.encoding="utf-8"
user_page=user_resp.text
with open("./user.html","w",encoding="utf-8") as fp:
fp.write(user_page)