【Python】学习笔记6-网络编程urllib,request,请求rul
1、发送get请求
# 方法A 使用urllib返回url请求
1 # res = urllib.request.urlopen(url) #发送请求 url= ‘http://www.。。。。。’ 2 # jieguo =res.read().decode() 3 # print(json.loads(jieguo)) #获取结果
# 方法B 使用request,相对简单
1 # req = requests.get(url) 2 # print(req.text) #字符串类型 3 # print(json.loads(req.text)) # 返回字典类型 等价于req.json 4 # print(req.json()) # 返回字典类型,req必须返回的是json串,才能使用此方法,很重要的方法
2、发送post请求
# req = requests.post(url,data) # print(req.json())
3、入参是json
# url = 'http://xxx'
# data = {'name':'222222','grade':'狮子座','phone':'x_900998732'}
# req = requests.post(url,json=data)
# 4、入参中含cookie
1 # 登陆取出cookie:6d195100b95a43046d2e385835c6e2c2 2 # cookie ={'xxx':'6d195100b95a43046d2e385835c6e2c2'} 3 # req = requests.post(url,data,cookies= cookie) 4 # print(req.json())
# # 5、添加header ,获取学生信息接口
1 # req = requests.get(url,headers={'header头':'值'}) 2 # print(req.json())
# 6、上传文件
1 # f = open(r'D:\BugReport.txt',encoding='utf-8') 2 # # f = open(r'笔记',encoding='utf-8') 3 # req = requests.post(url,files={'file':f}) #'file'参数名,参数值是一个文件类型 4 # print(req.json())
# 7、下载文件
1 # 2 # url ='http://fe0.jpg' #图片url 3 # r = requests.get(url) 4 # print(type(r)) #<class 'requests.models.Response'> 5 # print(r.status_code) #获取请求状态码 6 # print(r.content) #获取返回结果二进制格式 7 # fw = open('bt.jpg','wb') 8 # fw.write(r.content) 9 # fw.close()
# # 8、下载某个网页/视频,保存网页,类似简单爬虫
1 # url = 'http://www.xxxx' 2 # r = requests.get(url) 3 # f = open('aaa.html','wb') 放到本地这个文件中 4 # f.write(r.content) 5 # f.close()
# # 9、url编码
1 import urllib.parse 2 s = 'cm 刘星' 3 print('url编码:',urllib.parse.quote(s)) #输出url编码 4 # print(urllib.parse.quote_plus(s)) #输出url编码,编码内容会多,加强版 5 src = '%20%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95' 6 print('url解码:',urllib.parse.unquote(src)) #url解码 7 # print(urllib.parse.unquote_plus(src)) #url解码,加强版