python获取服务器响应cookie的实例
作者:我要七龙ru 时间:2023-06-14 15:02:50
总结
调试网站获取cookies时请查看,r.header和r.request.header这两个属性,因为cookie说不准出现在他们俩谁里面。
先贴一个代码
import re
import requests
from bs4 import BeautifulSoup
def printHeaders(headers):
for h in headers:
print(h+" : "+headers[h] + '\r\n')
def printCookies(cookies):
for h in cookies:
print(h+" : "+cookies[h] + '\r\n')
def loginFw(id,password):
url = "http://xxxxx/login.asp"
try:
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0',
'Host':'www.xxx.org',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Content-Type':'application/x-www-form-urlencoded',
'Referer':'http://xxx/login.asp',
'Connection':'keep-alive',
}
params = {"Reglname":id,"reglpassword":password}
r = requests.post(url,data=params,headers=headers)
printHeaders(r.request.headers) #服务器返回的cookie需要用r.request里的headers来获取
printHeaders(r.headers) #这里是获取不到服务器返回的cookie的
r.encoding = 'utf-8'
return r.text
except Exception as e:
print("登陆错误:"+str(e))
ret = loginFw("xxx@qq.com","xxx")
#print(ret)
事情经过
事情的发生是这样的,今天我在调试一个网站的模拟登陆,但是怎么调试都调试不出来这个网站返回的cookie(因为我是用r.headers来获取cookies的),后来我就在想是不是我的请求头没有设置正确,然后我就遍历了r.request.headers,然后这个变量如实的打印了我的请求头的信息,但是我仔细一看cookie怎么出现了变化,咦,这不就是我需要的响应cookie吗!
难道是我对r.request这个对象的理解出错了吗?以前我一直认为这个对象里面存储的是我请求发出去的信息,现在怎么会出现响应cookie呢?
就在我百撕不得其解的时候,我去翻阅了requests库的官方文档关于respond对象中包含的request的解释,它上面写着“The PreparedRequest object to which this is a response.”(表示看不到什么意思,百度翻译也翻译不清楚),咦,好像是和响应有关啊,看来应该是我的理解出现了错误。
更好的解决方案
那当然是用requests提供的"会话对象",他能够自动的保留请求所获取的参数。
具体请跳转传送门:
http://cn.python-requests.org/zh_CN/latest/user/advanced.html#request-and-response-objects
后来
后来我发现原来是因为我在请求头里面写了“Host”,“Referer”,导致Cookie出现异常的原因,所以以后不要随便写这两个参数了,要写就照着封包里的写。
来源:https://blog.csdn.net/a735311619/article/details/78093738
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
php连接微软MSSQL(sql server)完全攻略
![](https://img.aspxhome.com/file/2023/6/55426_0s.jpg)
Python百度指数获取脚本下载并保存
![](https://img.aspxhome.com/file/2023/8/67878_0s.webp)
python3实现无权最短路径的方法
![](https://img.aspxhome.com/file/2023/2/76872_0s.png)
CentOS7.6安装MYSQL8.0的步骤详解
![](https://img.aspxhome.com/file/2023/7/66607_0s.png)
WSC脚本部件技术:利用Javascript编写ActiveX控件
python3.6+django2.0开发一套学员管理系统
Python调用两个机器人聊天的实战
![](https://img.aspxhome.com/file/2023/9/124639_0s.png)
Pycharm 2020年最新激活码(亲测有效)
![](https://img.aspxhome.com/file/2023/6/59136_0s.png)
python 读写txt文件 json文件的实现方法
jupyter .ipynb转.py的实现操作
![](https://img.aspxhome.com/file/2023/6/133876_0s.jpg)
浅谈python中的多态
jQuery获取radio选中项的值实例
![](https://img.aspxhome.com/file/2023/3/137103_0s.jpg)
js substr支持中文截取函数代码(中文是双字节)
浅析Oracle中sys、system和Scott用户下的数据库连接问题
python lambda表达式(匿名函数)写法解析
Go系列教程之反射的用法
html风格tooltip效果的实现
详解python持久化文件读写
asp显示左边的n个字符自动识别汉字的函数
Python接口自动化 之用例读取方法总结
![](https://img.aspxhome.com/file/2023/3/90353_0s.png)