python使用笔记19--网络操作
1.get请求
1 import requests 2 import datetime 3 #get请求 4 url = 'http://api.nnzhp.cn/api/user/stu_info' 5 req = requests.get(url,params={'stu_name':'abc'}) 6 print(req.json())#返回的json直接帮你转成了字典 7 print(req.text)#返回的就是字符串,如果返回的不是json,就要用他了 8 print(req.status_code)#返回http的状态码 9 print(req.content)#返回bytes类型的,下载文件的时候用他
2.post请求
1 #post请求 2 url1="http://api.nnzhp.cn/api/user/login" 3 req1 = requests.post(url1,data={'username':'niuhanyang','passwd':'aA123456'}) 4 print(req1.json())
3.上传header,cookie
1 #发送header,cookie 2 url="https://qun.qq.com/cgi-bin/qun_mgr/get_group_list" 3 data = {'bkn':2087042978} 4 5 #第一种传cookie的方式:将cookie值转为字典,再当做参数传入 6 # d = {'pgv_pvi': '7783950336', ' pgv_pvid': '8908705984', ' RK': 'x9TQxyyNRp', ' ptcz': 'd3d09a82f55c4d70013f0c76c2999c164031500b8ad8275f2cedc1ad7eb6f645', ' o_cookie': '1123414020', ' pgv_si': 's2724760576', ' _qpsvr_localtk': '0.0546430314947981', ' uin': 'o1123414020', ' skey': '@B8DwKlUlP', ' p_uin': 'o1123414020', ' pt4_token': 'NpLWPKFVGpKOwzOwrim-645X*Y7Rb94Q0Inq*AMdFt0_', ' p_skey': 'DD4luaI4E2Br3138sblEuuiLgP8OmZL-ZaE6F6FzcsM_', ' traceid': 'd5d6556693'} 7 # req = requests.post(url,data,cookies=d) 8 # print(req.json()) 9 10 #第二种传cookie的方式:直接把cookie当做字符串,传入 11 header = {'cookie':'pgv_pvi=7783950336; pgv_pvid=8908705984; RK=x9TQxyyNRp; ptcz=d3d09a82f55c4d70013f0c76c2999c164031500b8ad8275f2cedc1ad7eb6f645; o_cookie=1123414020; pgv_si=s2724760576; _qpsvr_localtk=0.0546430314947981; uin=o1123414020; skey=@B8DwKlUlP; p_uin=o1123414020; pt4_token=NpLWPKFVGpKOwzOwrim-645X*Y7Rb94Q0Inq*AMdFt0_; p_skey=DD4luaI4E2Br3138sblEuuiLgP8OmZL-ZaE6F6FzcsM_; traceid=d5d6556693'} 12 req = requests.post(url,data,headers=header) 13 print(req.json())
4.上传json
1 #传json 2 url = 'https://oapi.dingtalk.com/robot/send?access_token=44402c9408df8cf3f429c02a20399fc34604f98cf572fcaeaa3f9592426176a7' 3 today = datetime.datetime.now() 4 d = {"msgtype": "text","text": {"content": "现在是%s,大家不要忘记写作业哦!暗号:besttest"%today} } 5 # d = {"msgtype": "text","text": {"content": "我就是我,不一样的烟火1111"} } 6 req = requests.post(url,json=d)#指定上传参数类型为json 7 print(req.json()) 8 print(req.cookies)#获取cookies
5.下载图片
1 #下载图片 2 url = 'https://q4.qlogo.cn/g?b=qq&nk=1123414020&s=140' 3 req = requests.get(url) 4 f = open('xxl.jpg','wb') 5 f.write(req.content) 6 f.close()
6.上传图片
#上传文件 url = 'http://127.0.0.1/api/file/file_upload' f = open('student.xls','rb') data = {'file': f} req = requests.post(url,files = data)#指定上传参数类型为files print(req.json()) f.close()