本文学习笔记整理自【Python开发】接口测试教程
一. dict与json
0. json扫盲
1. json是一种数据交换格式
2. json独立于编程语言
1. dict与json
1. python数据类型: type查看数据类型
2. dict与json类型对比
python | json |
dict | object |
list,tuple | array |
str,unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
3. dict与json互转(Note: 字典是无序的)
1 #coding:utf-8 2 3 import json 4 5 d = {"a":None, 6 "b":False, 7 "c":True, 8 "d":"Bab", 9 "e":{"f":1, 10 "g":"11", 11 "h":["1",12], 12 "i":("in",90)} 13 14 print(type(d)) 15 print("dict: %s"%d) 16 17 # 转化成json数据 18 d_json = json.dumps(d) 19 20 print(type(d_json)) 21 print("dict: %s"%d_json) 22 23 #服务的返回json, 将json转成dict 24 j_dict = json.loads(d_json)
二. json
1. 传json参数
post请求有两种方法传json参数(以下两种等价):
a. 直接传json参数(自动转json)
r1 = request.post(url,json=payload)
b. 传data参数(需json转换)
r2 = requests.post(url,data=json.dumps(payload)
2. json解析
1. Content是以字节方式输出, 用loads将json转换成dict: d = json.loads(res.content)
2. json()是将服务器返回的json类型转为dict: res.json()
3. json解析案例
1 # coding: utf-8 2 3 import requests 4 requests.packages.urllib3.disable_warnings() 5 6 header = { 7 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"} 8 9 url = "https://www.kuaidi100.com/query?type=zhongtong&postid=73124853607476" 10 11 res = requests.get(url=url, headers=header, verify=False) 12 13 # json解析成dict 14 res_dict = res.json() 15 print(res_dict) 16 17 # 获取最新一条快递信息 18 result = res_dict["data"][0]["context"] 19 20 if "已经签收" in result: 21 print("已经成功签收了") 22 else: 23 print("还没签收成功")
三. url
1. url编码与解码
Request自动处理url带中文的请求
1 # coding: utf-8 2 3 from urllib import parse 4 5 a = "中文" 6 # 转url编码 7 b = parse.quote(a) 8 url = "https://zzk.cnblogs.com/s/blogpost?w=%s" % b 9 print(url) 10 11 import requests 12 13 requests.packages.urllib3.disable_warnings() 14 15 # requests自动转换 16 r = requests.get("https://zzk.cnblogs.com/s/blogpost?w=%s" % a, verify=False) 17 print(r.url) 18 print(type(r.url)) 19 print(r.encoding) 20 # 解码 21 print(parse.unquote(r.url))
2. 参数关联
有时候下一个请求需要用到上一请求的参数, 如:博客园删除草稿
删除博客园草稿:
第一步: 登录
第二步: 创建草稿
第三步: 获取草稿ID
第四步: 根据获取的ID删除草稿
1 # coding: utf-8 2 import requests 3 4 s = requests.session() 5 # 第一步, 登录 6 login_url = "https://account.cnblogs.com/signin" 7 head = { 8 "Host": "i-beta.cnblogs.com", 9 "X-BLOG-ID": "553511", 10 "Sec-Fetch-Dest": "empty", 11 "DNT": "1", 12 "Sec-Fetch-Site": "same-origin", 13 "Sec-Fetch-Mode": "cors", 14 "Accept-Encoding": "gzip, deflate, br", 15 "Accept-Language": "zh-CN,zh;q=0.9", 16 "Connection": "keep-alive", 17 "Accept": "application/json, text/plain, */*", 18 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"} 19 login_res = s.get(url=login_url, headers=head, verify=False) 20 21 22 # 添加cookie 23 c = requests.cookies.RequestsCookieJar() 24 c.set("SyntaxHighlighter", "python") 25 c.set(".Cnblogs.AspNetCore.Cookies", 26 "CfDJ8Nf-Z6tqUPlNrwu2nvfTJEi5DJv_S6Y3UBLEFlVb0n3pFU3EnkUL5-f15OY58-u4RCoY5fCLQxPWQmmEqs3gjZIjDcAY2RxUw3s1rFhRmzVpOk-SRCjZQAJTLc-rewpX458ZRqLwPkEDn3hZXfbRRajcRzLFW1j55SbVPUU86Zf3VP4F70TzIzd4fVZnJBlvm0eu5b2K0p1E1h3X2XQh9UqJ4J9-f3p6AeSfAcvrHiD0TRMi8Uo2ZhZoGuU0rXxxdWrB_uTFeMA19t0S9tSkmxTgWiJvhxKKij0CrlJPV8xaX9SxK9QbF2rw_yycHd1zqWwnD3OiAU6aAwFlX6KgSyxR-tBjhrwe7yJ3ZFpTOvF-Rpr28Hpi-BwvAFfI_CsYNEQLE3ceelXIV8yHIjSSBC3pqXMu8nuFgQa6OZf139Jt4aLCUbc2TJLlu-a149qlRC8AEhk4P05g2ZP-DqmWZqT3qimx8hdS6k-8BoZNvCaSlOGbDbQ4KdKE3asqq8IB8snOwvOy-l2gQzTWOJDkeBcb5VLAdD9woAPT01Kgg5Y5", 27 ) 28 c.set(".CNBlogsCookie", 29 "1767FD5C44246E1484E1B1481D0FBA40D909BC74F7949838F7622E7F575023D5F9C137E904E235BAF3575F3B177C19D483071B93FB2BA6510A34B295EE9C497FB2C3E4857D02C1B5D5B16A527BC10AB90785D68E") 30 # 添加cookie到session 31 s.cookies.update(c) 32 33 34 # 第二步, 保存草稿 35 draft_url = "https://i-beta.cnblogs.com/api/posts" 36 37 data = {"id": None, "postType": 1, "title": "test1", "url": None, "postBody": "<p>test1</p>", "categoryIds": None, 38 "inSiteCandidate": False, "inSiteHome": False, "siteCategoryId": None, "blogTeamIds": None, 39 "isPublished": False, "displayOnHomePage": True, "isAllowComments": True, "includeInMainSyndication": True, 40 "isPinned": False, "isOnlyForRegisterUser": False, "isUpdateDateAdded": False, "entryName": None, 41 "description": None, "tags": None, "password": None, "datePublished": "2020-02-29T10:03:17.364Z", 42 "isMarkdown": False, "isDraft": True, "autoDesc": None, "changePostType": False, "blogId": 0, "author": None, 43 "removeScript": False, "ip": None, "changeCreatedTime": False, "canChangeCreatedTime": False} 44 45 draft_res = s.post(draft_url, json=data, headers=head, verify=False) 46 print(draft_res.url) 47 48 # 第三步,正则提取需要的参数值 49 return_data = draft_res.json() 50 draft_id = return_data["id"] 51 52 # 第四步, 删除草稿 53 delete_draft_url = "https://i-beta.cnblogs.com/api/posts/%s" %draft_id 54 delete_draft_res = s.delete(url=delete_draft_url, headers=head, verify=False) 55 print(delete_draft_res.status_code)