1. The json
module provides a very simple way to encode and decode data JSON. Two of the main functions are json.dumps()
and json.loads()
, other than the serialization library as much less pickle interface. The following shows how to convert a Python data structures to JSON:
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
json_str = json.dumps(data)
The following shows how to convert a JSON encoded string back to a Python data structure:
data = json.loads(json_str)
2. Simple get and post requests, use import requests
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
#通过在发送post请求时添加一个data参数,这个data参数可以通过字典构造成
import requests
data = {
"name":"zhaofan",
"age":23
}
response = requests.post("http://httpbin.org/post",data=data)
print(response.text)
3.GET method, and a custom header
# -* - coding: UTF-8 -* -
import urllib2
request = urllib2.Request("http://www.baidu.com/")
request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
response = urllib2.urlopen(request)
print response.getcode()
print response.geturl()
print response.read()
POST method, and a custom header
# -* - coding: UTF-8 -* -
import urllib2
import urllib
request = urllib2.Request("http://passport.cnblogs.com/login.aspx")
request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
data={"tbUserName":"test_username", "tbPassword":"test_password"}
response = urllib2.urlopen(request, urllib.urlencode(data))
print response.getcode()
print response.geturl()
print response.read()
4. The actual test scripting
# coding:utf-8
import json
import urllib2
import requests
class AddScores:
def __init__(self):
pass
def getToken(self): # 获取token值
url1 = 'xxxxx'#url
r1 = requests.get(url1)
self.tokenObj = json.loads(r1.text)#解码JSON数据
if self.tokenObj["result"] == "success":
print self.tokenObj["token"]
else:
print "failed"
return self.tokenObj["token"]
def personMess(self): # 获取个人信息
url2 = 'xxx' + self.getToken()
r2 = requests.post(url2)
print r2.text
def addSco(self,resId): # 添加分数
data = {
"memberId": "xxx",
"orgCode": "xxx",
"resourceId": resId,#传参,传resourceId
"configName": "wsp", "resourceType": "wsp"
}
print "添加分数的请求参数:"
print json.dumps(data)#编码JSON
headers = {'Content-Type': 'application/json'}
url3 = 'xxx' + self.getToken()
re3 = urllib2.Request(url=url3, headers=headers, data=json.dumps(data))
response = urllib2.urlopen(re3)
print response.read()
5. TXT file read and write
#coding:utf-8
import time
from Demo2.token import AddScores
class ResId:
def getResId(self):
file=open('xxxx')
# a=file.read()
# print a
lId= file.readline()
lId=lId.strip(',\n')
while lId != '':#逐行读取数据
print lId
addScores = AddScores()
addScores.getToken()
addScores.personMess()
addScores.addSco(lId)
time.sleep(68)
lId = file.readline()
print "============================="
ResId().getResId()