Python interface test study notes (five) - JSON

This article from finishing study notes [Python Interface Development Testing Tutorial

A. Dict and json

0. json Literacy

1. json is a data exchange format
2. json independent programming language

1. dict and json

1. python data types: type View data types

2. dict type contrast with json

python json
dict object
list,tuple array
str, unicode string
int, long, float number
True true
False false
None null

 

 

 

 

 

 

 3. dict and json system conversion (Note: the dictionary are unordered)

 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 is ],
 12 is  " I " :( " in " , 90 )}
 13 is  
14  Print (type (D))
 15  Print ( " dict:% S " % D)
 16  
. 17  # is converted into data json 
18 is d_json = json.dumps (D)
 . 19  
20 is  Print (type (d_json))
 21 is  Print ( " dict:% S " % d_json)
 22 is  
23 is  # services json return, to turn into a dict json
24 j_dict = json.loads(d_json)

Two. Json

1. json pass parameters

There are two ways mass post request json parameters (two equivalents):

a. json parameter directly transmitted (automatically transfer json)
         R1 = request.POST (URL, json = payload)
B. data transmission parameters (conversion required json)
         R2 = requests.post (URL, = json.dumps data (payload)

2. json parsing

1. Content byte is output by converting json loads into dict: d = json.loads (res.content)

2. json () is the type of json returned by the server into dict: res.json ()

3. json parsing Case

 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 resolved into dict 
14 res_dict = res.json ()
 15  Print (res_dict)
 16  
. 17  # to obtain the latest information on a delivery 
18 is Result = res_dict [ " Data " ] [0] [ " context " ]
 . 19  
20 is  IF  " has sign "  in the Result:
 21      Print ( " has been successfully sign up " )
 22  the else :
 23      Print ( " No sign success " )

Three. Url

1. url encoding and decoding

Automatic Request processing request url with the Chinese

 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. Parameters related

Sometimes the need to use the next request on a request parameters, such as: blog Garden delete drafts

Delete draft blog Park:

The first step: Log

Step 2: Create Draft

The third step: Get draft ID

Step four: Delete the draft according to the acquired 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 is  Print (draft_res.url)
 47  
48  # parameter values of the third step, is required to extract the 
49 return_data = draft_res.json ()
 50 draft_id return_data = [ " ID " ]
 51 is  
52 is  # fourth step, deleting the draft 
53 is delete_draft_url = " https://i-beta.cnblogs.com/api/posts/%s " % draft_id
 54 is delete_draft_res = s.delete (URL = delete_draft_url, headers = head, Verify = False)
 55  Print (delete_draft_res.status_code)
View Code

 

Guess you like

Origin www.cnblogs.com/fayez/p/12243755.html