python学习笔记17:网络操作-requests模块
一、安装第三方模块requests
安装命令为:
pip install requests
二、使用实例
1 import requests 2 3 # get请求 4 url = 'http://api.xxxxx.cn/api/user/stu_info' 5 req = requests.get(url,params={'stu_name':'abc'}) #params把参数传到url里面 6 print(req.json()) #返回的json自动转成字典 7 print(req.text) #返回的是字符串 8 print(req.status_code) #返回的http状态码 9 print(req.content) #返回的bytes类型的,适用于下载图片等二进制文件 10 11 # post请求 12 url = 'http://api.xxxx.cn/api/user/login' 13 req = requests.post(url,data={"username":"xxx","passwd":"123456"}) #date传的是body 14 print(req.json()) 15 16 # 发送header、cookie 17 url = 'https://qun.qq.com/cgi-bin/qun_mgr/get_group_list' 18 data = {"bkn":270223670} 19 # 方法一: 20 21 # s = 'RK=sIpJMSvZGd; ptcz=214c8af7f7269ddf8ef7b2f7d804441c6406bfbec8836dfce65cd30ec8558005; gr_user_id=e6b1f2b5-b344-47fe-9e0b-daedec912e15; pgv_pvi=2555754496; pgv_pvid=838986100; _qpsvr_localtk=0.8044086104004915; pgv_si=s9546202112; uin=o0875197774; skey=@kErZ5Q6dW; p_uin=o0875197774; pt4_token=UDFofMy9VA4hcOKtp5Fr4XB6yqI2QtyhPER966tbTRU_; p_skey=vl6LOtgwYPbzjIizqT*zCqSCpapANyuUC4EGBdQxMDY_; traceid=8aa9f34c3b' 22 # cookies = {} 23 # for c in s.split(';'): 24 # k,v = c.strip().split('=') 25 # cookies[k] = v 26 # print(cookies) 27 28 d = {'RK': 'sIpJMSvZGd', 'ptcz': '214c8af7f7269ddf8ef7b2f7d804441c6406bfbec8836dfce65cd30ec8558005', 'gr_user_id': 'e6b1f2b5-b344-47fe-9e0b-daedec912e15', 'pgv_pvi': '2555754496', 'pgv_pvid': '838986100', '_qpsvr_localtk': '0.8044086104004915', 'pgv_si': 's9546202112', 'uin': 'o0875197774', 'skey': '@kErZ5Q6dW', 'p_uin': 'o0875197774', 'pt4_token': 'UDFofMy9VA4hcOKtp5Fr4XB6yqI2QtyhPER966tbTRU_', 'p_skey': 'vl6LOtgwYPbzjIizqT*zCqSCpapANyuUC4EGBdQxMDY_', 'traceid': '8aa9f34c3b'} 29 req = requests.post(url,data,cookies = d) 30 # 方法二: 31 header = {'cookie':"RK=sIpJMSvZGd; ptcz=214c8af7f7269ddf8ef7b2f7d804441c6406bfbec8836dfce65cd30ec8558005; gr_user_id=e6b1f2b5-b344-47fe-9e0b-daedec912e15; pgv_pvi=2555754496; pgv_pvid=838986100; _qpsvr_localtk=0.2859211341770833; pgv_si=s6945303552; uin=o0875197774; skey=@Hn6Y7eKSR; p_uin=o0875197774; pt4_token=ZRb11e7z-BKj*3QpnZcKpsVsjoOhnzkkKnrfgPh-in4_; p_skey=o1tlsbkxMVfGzOONS7otBfEMUksEfNxz*QMIY3hmiiI_; traceid=d057adbd78"} 32 req = requests.post(url,data,headers =header ) 33 print(req.json()) 34 35 # 传json 36 url = "https://oapi.dingtalk.com/robot/send?access_token=2c9408df8cf3f429c02a2" 37 d = {"msgtype":"text","text":{"content":"123456 besttest"}} 38 req = requests.post(url,json=d) 39 print(req.json()) #获取返回数据 40 print(req.cookies) #获取cookies 41 42 # 下载文件 43 url = 'https://q4.qlogo.cn/g?b=qq&nk=875191111&s=140' 44 req = requests.get(url) 45 f = open('zx.jpg','wb') 46 f.write(req.content) 47 f.close() 48 49 #上传文件 50 url = "http://api.xxxx.cn/api/file/file_upload" 51 f = open('sxy.mp4','rb') 52 data = {'file':f} 53 r = requests.post(url,files=data) 54 print(r.json()) 55 f.close()