requests模块
2018-07-26 15:11 小娜_8337 阅读(154) 评论(0) 收藏 举报想要通过python来发送网络请求,可以使用内置的urllib2模块
但是requests模块使用起来更简洁
pip install requests
1、发送get请求
url1 = 'http://118.24.3.xx/api/user/stu_info' res = requests.get(url1,params={'stu_name':'xiaohei'})#发送get请求,params填写参数 print(res.json())#返回数据是json,把结果转为字典
2、发送post请求
url2 = 'http://118.24.3.xx/api/user/login' data = {"username":"niuhanyang","passwd":"aA123456"}#发送post请求,data填写参数 res = requests.post(url2,data=data) print(res.json())
3、发送post请求,json传参
url3 = 'http://118.24.3.xx/api/user/add_stu' data = { "name":"requeslina", "grade":"天蝎座", "phone":18611532955, "sex":"男", "age":28, "addr":"河南省济源市北海大道32号" } res = requests.post(url3,json=data)#post请求,json传参 print(res.json())
4、带cookies的请求
url4 = 'http://118.24.3.xx/api/user/gold_add' data = {'stu_id':15,'gold':200} cookie = {'niuhanyang':'abd9a0995f4696e1a60133220b32037a'} res = requests.post(url4,data=data,cookies=cookie)#带cookie的请求 print(res.json())#json直接把返回结果转成字典
5、带header的请求
url5 = 'http://118.24.3.xx/api/user/all_stu' header = {'Referer':'http://api.nnzhp.cn/'} res = requests.get(url5,headers=header)#带header的请求 print(res.json())#json直接把返回结果转成字典
6、字符串的响应数据
url6 = 'http://www.nnzhp.cn' res = requests.get(url6) print(res.text)#字符串的响应数据
7、请求获取二进制数据,可以用来下载
url7 ='http://qiniuuwmp3.changba.com/1084511584.mp3' res = requests.get(url7) print(res.content)#获取二进制的数据 with open('魔鬼中的天使.mp3','wb') as fw:#wb是写二进制的东西 rb读二进制的 fw.write(res.content) print(res.status_code)#响应状态码
8、下载一个图片
url8 ='https://aliimg.changba.com/cache/photo/855e5493-f018-44db-8892-c8660649327b_640_640.jpg' res = requests.get(url8,verify=False)#如果是https 加verify=False参数 with open('lina.jpg','wb') as fw: fw.write(res.content)
9、上传文件请求
url9 = "http://118.24.3.xx/api/file/file_upload" data = {'file':open('lina.jpg','rb')} res = requests.post(url9,files=data)#上传文件 print(res.text)
浙公网安备 33010602011771号