import json
import requests
class GetRequest:
def noParams(self):
url = "http://httpbin.org/get"
res = requests.get(url)
return res.text
def params(self):
url = "http://www.tuling123.com/openapi/api"
params = {"key": "ec961279f453459b9248f0aeb6600bbe", "info": "你好"}
res = requests.get(url=url, params=params)
return res.text
class PostRequest:
def fromType(self):
headers = {"Content-Type": "x-www-form-urlencoded"}
url = "http://httpbin.org/post"
data = {"name": "hanzhichao", "age": 18}
res = requests.post(url=url, data=data, headers=headers)
return res.text
def jsonType(self):
headers = {"Content-Type": "application/json"}
url = "http://httpbin.org/post"
data = json.dumps({"name": "hanzhichao", "age": 18})
res = requests.post(url=url, data=data, headers=headers)
return res.text
"""
Python中字典和JSON的区别:
字典是一种数据结构,JSON对象是一种通用JavaScript数据格式;
1、字典支持单引号和双引号,JSON只支持双引号;
2、字典中的True和False首字母大写,JSON中的true和false首字母小写;
3、字典中的空值为None,JSON中的空值为null;
JSON格式操作方法 和反序列化:
1、序列化(字典-->文本/文件句柄):json.dumps()/json.dump() 将Python字典转变为JSON对象
2、反序化(文本/文件句柄-->字典):json.loads()/json.load() 将JSON对象转换为Python字典
"""
class JsonTest:
def jsonDumps(self):
data = {'name': '张三', 'password': '123456', "male": True, "money": None}
res = json.dumps(data)
return res
def jsonLoads(self):
text = '{"name": "\u5f20\u4e09", "password": "123456", "male": true, "money": null}'
res = json.loads(text)
return (res, res['name'])
def jsonDump(self):
dict = {'name': '张三', 'password': '123456', "male": True, "money": None}
f = open("demo1.json", "w")
json.dump(dict, f)
f.close()
def jsonLoad(self):
f = open("demo2.json", 'r', encoding="utf-8")
dict = json.load(f)
print(dict['name'])
f.close()
if __name__ == '__main__':
print(JsonTest.jsonLoad(None))
requests库详解#
请求方法#
- requests.get()
- requests.post()
- requests.put()
...
- requests.session(): 用于保持会话(session)
除了requests.session()外,其他请求方法的参数都差不多,都包含url,params, data, headers, cookies, files, auth, timeout等等
请求参数#
- url: 字符串格式,参数也可以直接写到url中
- params:url参数,字典格式
- data: 请求数据,字典或字符串格式
- headers: 请求头,字典格式
- cookies: 字典格式,可以通过携带cookies绕过登录
- files: 字典格式,用于混合表单(form-data)中上传文件
- auth: Basic Auth授权,数组格式
auth=(user,password)
- timeout: 超时时间(防止请求一直没有响应,最长等待时间),数字格式,单位为秒
响应解析#
- res.status_code: 响应的HTTP状态码
- res.reason: 响应的状态码含义
- req.text:响应的文本格式,按req.encoding解码
- req.content: 响应的二进制格式
- req.encoding: 解码格式,可以通过修改
req.encoding='utf-8'来解决一部分中文乱码问题
- req.apparent_encoding:真实编码,由chardet库提供的明显编码
- req.json(): (注意,有括号),响应的json对象(字典)格式,慎用!如果响应文本不是合法的json文本,或报错
- req.headers: 响应头
- req.cookies: 响应的cookieJar对象,可以通过
req.cookies.get(key)来获取响应cookies中某个key对应的
import requests
res = requests.get("https://www.baidu.com")
print(res.status_code, res.reason)
print(res.text)
print(res.content)
print(res.encoding)
print(res.apparent_encoding)
res.encoding = 'utf-8'
print(res.text)
print(res.cookies.items())
print(res.cookies.get("BDORZ"))
import jsonpath
s = {
"data": {
"status": 1,
"user": {
"id": "leilei_id_66666",
"account_name": "leilei",
"nick_name": "leilei",
"token": "da335ef2a9579c84927c90a002162490",
"menu": "["客户管理","/customer/serviceList","/customer/newService","/customer/customerList","/customer/serviceUpdate","/customer/health","/progressManagement/riskListNew","/progressManagement/taskMark","/capricorn","/progressManagement/taskIntervention","/progressManagement/reform","/progressManagement/riskAccidentEvent","/progressManagement/pptList","/progressManagement/riskDealListNew","/progressManagement/securityEventList","/progressManagement/markTable","/progressManagement/interventionTable","/progressManagement/newMark","/progressManagement/newIntervention","/progressManagement/voiceDownloadLog","胎温胎压处理","/progressManagement/tires/monitor","/progressManagement/tires/statistics","/progressManagement/CameraCoverAbnormal","/progressManagement/NotRun","/progressManagement/maintenanceList","保险服务","/insurance/caseTracingView","/insurance/caseRecords","/insurance/accident","/security/weeklyTest","/security/newWeekly","/security/analysis","/security/tangDoubleList","/security/wechatGroupSending","/security/wechatTable","/security/wechatMessageTable","信息管理","/infoManagement/mailList","一键报修","/fixed/index","健康度","/productHealth/productHealthIndex","/productHealth/abnormalTrends","/productHealth/equipmentMonitoringCenter","/authority/userList","/authority/roleConfig","/authority/PMmanagement","/authority/team","操作日志","/logs/logHistory"]"
}
},
"code": 0,
"msg": "success",
"time": 1615969440.276317
}
r1 = jsonpath.jsonpath(s, '$.code')
r2 = jsonpath.jsonpath(s, '$.data.user.id')
r3 = jsonpath.jsonpath(s, '$..token')
print(r3)