如何使用python从json对象中提取键名为Set-cookie的值?
时间: 2024-03-03 13:52:40 浏览: 20
可以使用Python中的json和requests库来实现。
假设json对象存储在变量response中,可以使用以下代码提取键名为Set-Cookie的值:
```python
import json
import requests
response = requests.get(url) # 发送请求并获取响应
json_obj = json.loads(response.text) # 将响应转换为json对象
set_cookie_value = json_obj.get('headers', {}).get('Set-Cookie', '') # 获取Set-Cookie的值
```
其中,使用`json.loads`将响应转换为json对象,然后使用`get`方法获取键名为Set-Cookie的值。如果Set-Cookie不存在,则返回空字符串。
相关问题
请求 请求头 POST /api/sign Content-Type: application/json 消息体 为json格式 { "action" : "signin", "username" : "xxxx", "password" : "yyyy" } 响应 响应头 200 OK Content-Type: application/json Set-Cookie: sessionid=<sessionid数值> 消息体 如果校验通过,返回消息如下 { "ret": 0, "usertype":1, "userid":1, "realname":"白月黑羽", } ret 为 0 表示登录成功 usertype 是用户类型。 1:管理员,2000:学生,3000:老师 userid 是用户在系统中的id realname 是用户的姓名 登录成功后, 服务端在消息头Set-Cookie 中存入sessionid ,该用户的后续请求头Cookie中必须携带sessionid。 如果登录校验失败,返回失败的原因,示例如下 { "ret": 1, "msg": "用户名或者密码错误" } ret 不为 0 表示登录失败, msg字段描述登录失败的原因 根据登录接口写一个requests库的接口自动化脚本
好的,以下是一个使用 requests 库编写的自动化脚本:
```python
import requests
url = 'http://localhost:8000/api/sign'
headers = {
'Content-Type': 'application/json'
}
data = {
'action': 'signin',
'username': 'xxxx',
'password': 'yyyy'
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
cookie = response.cookies.get('sessionid')
if cookie:
print('登录成功!')
print('cookie:', cookie)
result = response.json()
print('ret:', result['ret'])
print('usertype:', result['usertype'])
print('userid:', result['userid'])
print('realname:', result['realname'])
else:
print('登录失败!Cookie未获取到!')
else:
print('登录失败!状态码:', response.status_code)
```
需要注意的是,由于请求头中需要携带 Cookie,因此在登录成功后,需要获取响应头中的 sessionid 值,并在后续的请求头中添加 Cookie。
from mitmproxy import http from mitmproxy.tools.main import mitmdump import temp import json class AddHeader: def __init__(self): self.num = 0 self.file = open("./request_headers.txt", "w") # 打开文件对象 def request(self, flow: http.HTTPFlow) -> None: with open('temp.json', 'r') as fff: config = json.load(fff) self.num += 1 # 保存请求头部内容和请求URL到文件 if f"{config['get_url']}" in flow.request.pretty_url: for name, value in flow.request.headers.items(): if f"{config['keyword']}" in name: self.file.write(f"{value}") self.file.flush() # 立即写入文件 # exit(0) def done(self): self.file.close() # 关闭文件对象 addons = [ AddHeader() ] if __name__ == "__main__": # print(config['get_url']) # print(config['keyword']) mitmdump(['-p', '8081', '-s', __file__]) 将写入request_headers.txt修改为写入到一个名为cookie.json的json文件中,把写入的值作为cookie.json中cookie的值,cookie.json如下: { "cookie": "" }
这段代码是使用 mitmproxy 中的 AddHeader 插件来获取 HTTP 请求的特定头部信息,并将其写入文件中。你的问题是将这个插件修改,不再将信息写入文件,而是将它们写入一个名为 cookie.json 的 JSON 文件中,并将其作为 cookie 的值。你需要将 AddHeader 插件修改为以下内容:
```python
import json
from mitmproxy import http
class AddCookie:
def __init__(self):
with open('cookie.json', 'r+') as f:
try:
self.cookies = json.load(f)
except json.JSONDecodeError:
self.cookies = {}
f.seek(0)
f.write(json.dumps(self.cookies))
f.truncate()
def request(self, flow: http.HTTPFlow):
if 'cookie' in self.cookies:
flow.request.headers['Cookie'] = self.cookies['cookie']
def response(self, flow: http.HTTPFlow):
if 'set-cookie' in flow.response.headers:
self.cookies['cookie'] = flow.response.headers['set-cookie']
with open('cookie.json', 'w') as f:
json.dump(self.cookies, f)
```
这个插件的作用是将请求中的 cookie 设置为 cookie.json 文件中的值,并将响应中的 set-cookie 头部中的 cookie 值更新为 cookie.json 文件中的值。请注意,这个插件需要在 mitmproxy 中以 AddCookie 插件名运行。你可以使用以下命令来运行它:
```
mitmdump -s your_script.py -s AddCookie
```