欢迎使用ShowDoc!
```shell
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式
JSON的诞生原因是因为XML整合到HTML中各个浏览器实现的细节不尽相同,所以道格拉斯·克罗克福特(Douglas Crockford) 和 奇普·莫宁斯达(Chip Morningstar)
一起从JS的数据类型中提取了一个子集,作为新的数据交换格式,因为主流的浏览器使用了通用的JavaScript引擎组件,所以在解析这种新数据格式时就不存在兼容性问题,
于是他们将这种数据格式命名为 “JavaScript Object Notation”,缩写为 JSON,由此JSON便诞生了!
1、json语法规则
?数据在名称/值对中
?数据用逗号分隔
?花括号保存对象
?方括号保存数组
2、json名称/值对
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值,例:
“firstname”:“json”
3、json数据类型
?数字(整数、浮点数)
?字符串(在双引号中)
?逻辑值(true或false)
?数组(在方括号中)
?对象(在花括号中)
?null
4、json对象
在花括号中书写,对象可以包含多个名称/值对,例:
{“firstname”:“jonh”,“lastname”:“Doe”}
5、json数组
employees是包含三个对象的数组。每个对象代表一条关于某个人名的记录,在方括号中书写,数组可以包含多个对象:
{
“employees”:[
{ “firstName”:“John” , “lastName”:“Doe” },
{ “firstName”:“Anna” , “lastName”:“Smith” },
{ “firstName”:“Peter” , “lastName”:“Jones” }
]
}
import json
常用的四个:json.dump json.dumps json.load json.loads
dumps是将dict转化成str格式,
loads是将str转化成dict格式
dump和load也是类似的功能,只是与文件操作结合起来了,主要用来读写json文件
# json.dump()函数的使用,将json信息写进文件
json_info = "{‘age‘: ‘12‘}"
file = open(‘1.json‘,‘w‘,encoding=‘utf-8‘)
json.dump(json_info,file)
# json.load()函数的使用,将读取json信息
file = open(‘1.json‘,‘r‘,encoding=‘utf-8‘)
info = json.load(file)
print(info)
(1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码---序列化
#python的列表转换为json的数组
>>> import json
>>> json.dumps([1,2,3])
‘[1, 2, 3]‘
#python的字符串转换为json的字符串
>>> json.dumps(‘abdcs‘)
‘"abdcs"‘
#python的元祖转换为json的数组
>>> json.dumps((1,2,3,‘a‘))
‘[1, 2, 3, "a"]‘#注意此时显示的是方括号
#python的字典转换为json的对象
>>> json.dumps({1:‘a‘,2:‘b‘})
‘{"1": "a", "2": "b"}‘#注意此时1和2转换后是加了引号的,因为json的名称是必须要加引号的
#python的整数转换为json的数字
>>> json.dumps(13)
‘13‘
#python的浮点数转换为json的数字
>>> json.dumps(3.1415)
‘3.1415‘
#python的unicode字符串转换为json的字符串
>>> json.dumps(u‘a‘)
‘"a"‘
#python的True转换为json的数组true
>>> json.dumps(True)
‘true‘
#python的False转换为json的数组false
>>> json.dumps(False)
‘false‘
#python的None转换为json的null
>>> json.dumps(None)
‘null‘
#json本质上是一个字符串
>>> type(json.dumps(‘abc‘))
<class ‘str‘>
--json.dumps方法提供了很多好用的参数可供选择,比较常用的有sort_keys,indent、separator、skipkeys、ensure_ascii等参数
语法:
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
**1、sort_keys(对dict对象(a到z)进行排序),sort_keys等于True表示升序:
data1 = {‘b‘:789,‘c‘:456,‘a‘:123}
data2 = {‘a‘:123,‘b‘:789,‘c‘:456}
d1 = json.dumps(data1,sort_keys=True)
d2 = json.dumps(data2)
d3 = json.dumps(data2,sort_keys=True)
print (d1)
print (d2)
print (d3)
print (d1==d2)
print (d1==d3)
输出:
{"a": 123, "b": 789, "c": 456}
{"a": 123, "c": 456, "b": 789}
{"a": 123, "b": 789, "c": 456}
False
True
**2、indent(根据数据格式缩进显示,读起来更清晰,indent的数值表示缩进的位数)
data1 = {‘b‘:789,‘c‘:456,‘a‘:123}
d1 = json.dumps(data1,sort_keys=True,indent=4)
print (d1)
输出:
{
"a": 123,
"b": 789,
"c": 456
}
输出的数据被格式化之后,变得可读性更强,但是却是通过增加一些冗余的空白格来进行填充的
**3、json主要是作为一种数据通信的格式存在的,而网络通信是很在乎数据的大小的,无用的空格会占据很多通信带宽,所以适当时候也要对数据进行压缩。
separator参数可以起到这样的作用,该参数传递是一个元组,包含分割对象的字符串---去掉逗号“,”和冒号“:”后面的空格
data = {‘a‘: 123, ‘c‘: 456, ‘b‘: 789}
print ‘DATA:‘, repr(data)
print ‘repr(data) :‘, len(repr(data))
print ‘dumps(data) :‘, len(json.dumps(data))
print ‘dumps(data, indent=2) :‘, len(json.dumps(data, indent=4))
print ‘dumps(data, separators):‘, len(json.dumps(data, separators=(‘,‘,‘:‘)))
输出:
DATA: {‘a‘: 123, ‘c‘: 456, ‘b‘: 789}
repr(data) : 30
dumps(data) : 30
dumps(data, indent=2) : 46
dumps(data, separators): 25
通过移除多余的空白符,达到了压缩数据的目的
**4、skipkeys,默认为False。 dumps方法存储dict对象时,dict的对象只能是基本数据类似(int,float,bool,None,str)【key必须是str类型】,如果出现了其他类型的话,那么会产生TypeError异常,如果开启该参数,设为True的话,则会比较优雅的过度
data = {‘b‘:789,‘c‘:456,(1,2):123}
print json.dumps(data,skipkeys=True)
输出:
{"c": 456, "b": 789}
**5、ensure_ascii :输出真正的中文需要指定ensure_ascii=False(json.dumps 序列化时对中文默认使用的ascii编码,无任何配置,或者说使用默认配置,输出的会是中文的ASCII字符码,而不是真正的中文)
import json
print json.dumps(‘凉凉‘)
>> "\u51c9\u51c9"
print json.dumps(‘凉凉‘, ensure_ascii=False)
>> 凉凉
dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
dump比较:入参多了一个fp表示filepath,最后多了一个写入文件的操作。
dict-{‘a‘: 123, ‘c‘: 456, ‘b‘: 789}
with open("test.json", "w", encoding=‘utf-8‘) as f:
# indent 超级好用,格式化保存字典,默认为None,小于0为零个空格
f.write(json.dumps(dict, indent=4))
json.dump(dict, f, indent=4) # 传入文件描述符,和dumps一样的结果
(2)json.loads()函数是将json格式数据转换为python对象 ---反序列化
语法:
json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
refer_to:https://blog.csdn.net/daerzei/article/details/100598901
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON # 把一个字符串反序列化为Python对象,这个字符串可以是str类型的,也可以是unicode类型的
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding # 如果参数s是以ASCII编码的字符串,那么需要手动通过参数encoding指定编码方式,
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name # 不是以ASCII编码的字符串,是不被允许的,你必须把它转为unicode
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the # object_hook参数是可选的,它会将(loads的)返回结果字典替换为你所指定的类型
result of any object literal decode (a ``dict``). The return value of # 这个功能可以用来实现自定义解码器,如JSON-RPC
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the # object_pairs_hook参数是可选的,它会将结果以key-value列表的形式返回
result of any object literal decoded with an ordered list of pairs. The # 形式如:[(k1, v1), (k2, v2), (k3, v3)]
return value of ``object_pairs_hook`` will be used instead of the ``dict``. # 如果object_hook和object_pairs_hook同时指定的话优先返回object_pairs_hook
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
``parse_float``, if specified, will be called with the string # parse_float参数是可选的,它如果被指定的话,在解码json字符串的时候,
of every JSON float to be decoded. By default this is equivalent to # 符合float类型的字符串将被转为你所指定的,比如说你可以指定为decimal.Decimal
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string # parse_int参数是可选的,它如果被指定的话,在解码json字符串的时候,
of every JSON int to be decoded. By default this is equivalent to # 符合int类型的字符串将被转为你所指定的,比如说你可以指定为float
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the # parse_constant参数是可选的,它如果被指定的话,在解码json字符串的时候,
following strings: -Infinity, Infinity, NaN. # 如果出现以以下字符串: -Infinity, Infinity, NaN 那么指定的parse_constant方法将会被调用到
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` # 你也可以用cls参数通过实现一个JSONDecoder的子类,来代替JSONDecoder,通过这个功能你可以自定义上面的那些parse_xxx参数,这里就不举例了
kwarg; otherwise ``JSONDecoder`` is used.
"""
注意:
json格式的字符串解码成Python对象以后,String类型都变成了Unicode类型,数组变成了list,不会回到原来的元组类型,字典key的字符类型也被转成Unicode类型
json模块会根据你的字符串自动转为最符合的数据类型,但如果参数不是json格式,否则会报json.decoder.JSONDecodeError错误: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
比较:
with open("test.json", "r", encoding=‘utf-8‘) as f:
data2 = json.loads(f.read()) # loads的传入参数为字符串类型
print(data2, type(data2))
f.seek(0) # 将文件游标移动到文件开头位置
data3 = json.load(f) #load的传入参数为文件流
print(data3, type(data3))
>>{‘name‘: ‘Tom‘, ‘age‘: 23} <class ‘dict‘>
**如何从Json中提取某个数据
s = json.loads(‘{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}‘)
print (s)
print (s.keys())
print (s["name"])
print (s["type"]["name"])
print (s["type"]["parameter"][1])
>>{‘name‘: ‘test‘, ‘type‘: {‘name‘: ‘seq‘, ‘parameter‘: [‘1‘, ‘2‘]}}
>>dict_keys([‘name‘, ‘type‘])
>>test
>>seq
>>2
遍历:
import json
test=u‘‘‘{"message":"ok","nu":"773022557706794","ischeck":"0","condition":"00","com":"shentong","status":"200","state":"0","data":[{"time":"2020-01-12 23:37:44","ftime":"2020-01-12 23:37:44","context":"[沈阳市]沈阳市【沈阳转运中心】,正发往【凤城市】","location":"沈阳市"},{"time":"2020-01-12 23:25:15","ftime":"2020-01-12 23:25:15","context":"[沈阳市]到沈阳市【沈阳转运中心】","location":"沈阳市"},{"time":"2020-01-11 01:20:11","ftime":"2020-01-11 01:20:11","context":"[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】","location":"郑州市"},{"time":"2020-01-11 01:13:16","ftime":"2020-01-11 01:13:16","context":"[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】","location":"郑州市"},{"time":"2020-01-10 22:30:26","ftime":"2020-01-10 22:30:26","context":"[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】","location":"郑州市"},{"time":"2020-01-10 22:25:51","ftime":"2020-01-10 22:25:51","context":"[郑州市]到郑州市【郑州转运中心】","location":"郑州市"},{"time":"2020-01-09 16:51:27","ftime":"2020-01-09 16:51:27","context":"[洛阳市]洛阳市【洛阳集散中心】,正发往【郑州转运中心】","location":"洛阳市"},{"time":"2020-01-09 16:51:16","ftime":"2020-01-09 16:51:16","context":"[洛阳市]到洛阳市【洛阳集散中心】","location":"洛阳市"},{"time":"2020-01-09 12:13:43","ftime":"2020-01-09 12:13:43","context":"[济源市]济源市【玉泉区分部】,【张超超/18790042837】已揽收","location":"济源市"}]}‘‘‘
json_1=json.loads(test)
json_2=json.dumps(json_1,ensure_ascii=False,indent=4)
#json中的索引
print(json_1[‘data‘])
print(json_2)
#json中的遍历
for itme in json_1[‘data‘]:
print(itme)
#把json转为字典,进行遍历
ls_all=[]
for dic in json_1[‘data‘]:
ls=[]
for k,v in dict(dic).items():
#这里的dic[k]和v是同一个变量
print(dic[k],end=‘ ‘)
ls.append(v)
print()
#把一个列表放入另一个列表
ls_all.append(ls)
print(ls_all)
>>
{‘time‘: ‘2020-01-12 23:37:44‘, ‘ftime‘: ‘2020-01-12 23:37:44‘, ‘context‘: ‘[沈阳市]沈阳市【沈阳转运中心】,正发往【凤城市】‘, ‘location‘: ‘沈阳市‘}
{‘time‘: ‘2020-01-12 23:25:15‘, ‘ftime‘: ‘2020-01-12 23:25:15‘, ‘context‘: ‘[沈阳市]到沈阳市【沈阳转运中心】‘, ‘location‘: ‘沈阳市‘}
{‘time‘: ‘2020-01-11 01:20:11‘, ‘ftime‘: ‘2020-01-11 01:20:11‘, ‘context‘: ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘location‘: ‘郑州市‘}
{‘time‘: ‘2020-01-11 01:13:16‘, ‘ftime‘: ‘2020-01-11 01:13:16‘, ‘context‘: ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘location‘: ‘郑州市‘}
{‘time‘: ‘2020-01-10 22:30:26‘, ‘ftime‘: ‘2020-01-10 22:30:26‘, ‘context‘: ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘location‘: ‘郑州市‘}
{‘time‘: ‘2020-01-10 22:25:51‘, ‘ftime‘: ‘2020-01-10 22:25:51‘, ‘context‘: ‘[郑州市]到郑州市【郑州转运中心】‘, ‘location‘: ‘郑州市‘}
{‘time‘: ‘2020-01-09 16:51:27‘, ‘ftime‘: ‘2020-01-09 16:51:27‘, ‘context‘: ‘[洛阳市]洛阳市【洛阳集散中心】,正发往【郑州转运中心】‘, ‘location‘: ‘洛阳市‘}
{‘time‘: ‘2020-01-09 16:51:16‘, ‘ftime‘: ‘2020-01-09 16:51:16‘, ‘context‘: ‘[洛阳市]到洛阳市【洛阳集散中心】‘, ‘location‘: ‘洛阳市‘}
{‘time‘: ‘2020-01-09 12:13:43‘, ‘ftime‘: ‘2020-01-09 12:13:43‘, ‘context‘: ‘[济源市]济源市【玉泉区分部】,【张超超/18790042837】已揽收‘, ‘location‘: ‘济源市‘}
2020-01-12 23:37:44 2020-01-12 23:37:44 [沈阳市]沈阳市【沈阳转运中心】,正发往【凤城市】 沈阳市
2020-01-12 23:25:15 2020-01-12 23:25:15 [沈阳市]到沈阳市【沈阳转运中心】 沈阳市
2020-01-11 01:20:11 2020-01-11 01:20:11 [郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】 郑州市
2020-01-11 01:13:16 2020-01-11 01:13:16 [郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】 郑州市
2020-01-10 22:30:26 2020-01-10 22:30:26 [郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】 郑州市
2020-01-10 22:25:51 2020-01-10 22:25:51 [郑州市]到郑州市【郑州转运中心】 郑州市
2020-01-09 16:51:27 2020-01-09 16:51:27 [洛阳市]洛阳市【洛阳集散中心】,正发往【郑州转运中心】 洛阳市
2020-01-09 16:51:16 2020-01-09 16:51:16 [洛阳市]到洛阳市【洛阳集散中心】 洛阳市
2020-01-09 12:13:43 2020-01-09 12:13:43 [济源市]济源市【玉泉区分部】,【张超超/18790042837】已揽收 济源市
[[‘2020-01-12 23:37:44‘, ‘2020-01-12 23:37:44‘, ‘[沈阳市]沈阳市【沈阳转运中心】,正发往【凤城市】‘, ‘沈阳市‘], [‘2020-01-12 23:25:15‘, ‘2020-01-12 23:25:15‘, ‘[沈阳市]到沈阳市【沈阳转运中心】‘, ‘沈阳市‘], [‘2020-01-11 01:20:11‘, ‘2020-01-11 01:20:11‘, ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘郑州市‘], [‘2020-01-11 01:13:16‘, ‘2020-01-11 01:13:16‘, ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘郑州市‘], [‘2020-01-10 22:30:26‘, ‘2020-01-10 22:30:26‘, ‘[郑州市]郑州市【郑州转运中心】,正发往【沈阳转运中心】‘, ‘郑州市‘], [‘2020-01-10 22:25:51‘, ‘2020-01-10 22:25:51‘, ‘[郑州市]到郑州市【郑州转运中心】‘, ‘郑州市‘], [‘2020-01-09 16:51:27‘, ‘2020-01-09 16:51:27‘, ‘[洛阳市]洛阳市【洛阳集散中心】,正发往【郑州转运中心】‘, ‘洛阳市‘], [‘2020-01-09 16:51:16‘, ‘2020-01-09 16:51:16‘, ‘[洛阳市]到洛阳市【洛阳集散中心】‘, ‘洛阳市‘], [‘2020-01-09 12:13:43‘, ‘2020-01-09 12:13:43‘, ‘[济源市]济源市【玉泉区分部】,【张超超/18790042837】已揽收‘, ‘济源市‘]]
>>
requests
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,
使用Requests可以轻而易举的完成浏览器可有的任何操作。
requests库特性:
Keep-Alive & 连接池
国际化域名和 URL
带持久 Cookie 的会话
浏览器式的 SSL 认证
自动内容解码
基本/摘要式的身份认证
优雅的 key/value Cookie
自动解压
Unicode 响应体
HTTP(S) 代理支持
文件分块上传
流下载
连接超时
分块请求
支持 .netrc
python---Requests库
--pip install requests
发送请求与传递参数
import requests
-------requests.get(url):url为https时,一直报错
问题原因是:https请求没有忽略ssl认证,
解决办法:在请求头中加verify=False,完美解决: requests.get("https://www.baidu.com", verify=False)
r = requests.get(url=‘http://www.itwhy.org‘) # 最基本的GET请求
print(r.status_code) # 获取返回状态
r = requests.get(url=‘http://dict.baidu.com/s‘, params={‘wd‘:‘python‘}) #带参数的GET请求
print(r.url)
***
requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求
import requests
response = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))
很多情况下的网站如果直接response.text会出现乱码的问题,所以这个使用response.content
这样返回的数据格式其实是二进制格式,然后通过decode()转换为utf-8,这样就解决了通过response.text直接返回显示乱码的问题.
关于响应内容-----Response对象使用
r.url #打印输出该 URL
r.status_code #返回连接状态,200正常。
r.text #默认以unicode形式返回网页内容,也就是网页源码的字符串。
r.content #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
r.encoding #获取当前的编码
r.encoding = ‘ISO-8859-1‘ #指定编码,r.text返回的数据类型,写在r.text之前。
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read()
r.ok # 查看r.ok的布尔值便可以知道是否登陆成功
#*特殊方法*#
r.json() #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常
r.raise_for_status() #失败请求(非200响应)抛出异常
r.headers #返回字典类型,头信息
r.requests.headers #返回发送到服务器的头信息
r.cookies #返回cookie
r.history #返回重定向信息,当然可以在请求是加上allow_redirects = false 阻止重定向
r = requests.get(‘url‘,timeout=1) #设置秒数超时,仅对于连接有效
请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 response.encoding 属性来改变它.如:
response =requests.get("http://www.baidu.com")
response.encoding="utf-8"
print(response.text)
不管是通过response.content.decode("utf-8)的方式还是通过response.encoding="utf-8"的方式都可以避免乱码的问题发生
Get 请求
*发送无参数的get请求 设置超时时间 timeout 单位秒
r = requests.get(‘http://www.baidu.com‘, timeout=1)
*发送带参数的请求.
字典:Requests 允许使用 params 关键字参数,以一个字符串字典来提供这些参数
payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
r = requests.get("https://www.baidu.com/", params=payload)
print(r.url)
https://www.baidu.com/?key2=value2&key1=value1
列表:
payload = {‘key1‘: ‘value1‘, ‘key2‘: [‘value2‘, ‘value3‘]}
r = requests.get(‘http://www.baidu.com/‘, params=payload)
print(r.url)
http://www.baidu.com/?key2=value2&key2=value3&key1=value1
**定制请求头、cookie:想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了
url = ‘https://www.baidu.com/s?wd=python‘
headers = {
‘Content-Type‘: ‘text/html;charset=utf-8‘,
‘User-Agent‘ : ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64)‘
}
cookie = {‘key‘:‘value‘}
r = requests.get(url,headers=headers,cookies=cookie)
*设置访问代理
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.100:4444",
}
r = requests.get(‘http://m.ctrip.com‘, proxies=proxies)
#如果代理需要用户名和密码,则需要这样:
proxies = {
"http": "http://user:pass@10.10.1.10:3128/",
}
POST 请求
HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式,服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,
再对消息主体进行解析。具体的编码方式包括:
1.最常见post提交数据的方式,以form表单形式提交数据
application/x-www-form-urlencoded
2.以json串提交数据。
application/json
3.一般使用来上传文件
multipart/form-data
实例如下:json.dumps()用于将字典形式的数据转化为字符串,json.loads()用于将字符串形式的数据转化为字典
1. 以form形式发送post请求
Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可
复制代码
payload = {‘key1‘: ‘value1‘,
‘key2‘: ‘value2‘
}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
...
"form": {
"key1": "value1",
"key2": "value2"
},
...
复制代码
2. 以json形式发送post请求
可以将一 json串传给requests.post()的data参数,
复制代码
url = ‘http://httpbin.org/post‘
payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
r = requests.post(url, data=json.dumps(payload))
#print(r.text)
print(r.headers.get(‘Content-Type‘))
application/json
复制代码
3. 以multipart形式发送post请求
Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可,文本文件report.txt的内容只有一行:Hello world!,从请求的响应结果可以看到数据已上传到服务端中。
复制代码
url = ‘http://httpbin.org/post‘
files = {‘file‘: open(‘report.txt‘, ‘rb‘)}
r = requests.post(url, files=files)
print(r.text)
{
...
"files": {
"file": "hello world"
},
"form": {},
"headers": {
"Content-Type": "multipart/form-data; boundary=6db46af64e694661985109da21c8fe9b",
},
"json": null,
"origin": "223.72.217.138",
"url": "http://httpbin.org/post"
...
}
上传文件:
import requests
url = ‘http://127.0.0.1:8080/upload‘
files = {‘file‘: open(‘/home/rxf/test.jpg‘, ‘rb‘)}
#files = {‘file‘: (‘report.jpg‘, open(‘/home/lyb/sjzl.mpg‘, ‘rb‘))} #显式的设置文件名
r = requests.post(url, files=files)
print(r.text)
```
原文:https://www.cnblogs.com/hd56/p/14744913.html