python-requests模块
Posted tour8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-requests模块相关的知识,希望对你有一定的参考价值。
1、get请求
1 import requests 2 3 # get请求 4 url = ‘http://api.nnzhp.cn/api/user/stu_info‘ 5 res = requests.get(url,params={‘stu_name‘:‘abc‘}) 6 print(res.json()) # 返回的json直接转成了字典 7 print(res.text) # 返回的就是字符串 8 9 print(res.status_code) # 返回的http状态码 10 11 print(res.content) # 返回的bytes类型,下载文件时用它 12 13 print(req.cookies) # 获取cookie
2、post请求
import requests # post请求 url = "http://api.nnzhp.cn/api/user/login" res = requests.post(url,data={"username":"xxx","passwd":"xxx"}) print(res.json())
3、传入cookie
- 通过参数cookies传递
import requests url=‘http://qun.qq.com/cgi-bin/qun_mgr/get_group_list‘ data = {"bkn":208992859} # 方法一:传cookie,通过cookies参数 # cookie,字典形式 d = {} res = requests.post(url,data,cookies=d) print(res.json())
- 通过headers传递
import requests url=‘http://qun.qq.com/cgi-bin/qun_mgr/get_group_list‘ data = {"bkn":208992859} #方法二:通过headers参数;抓包获取cookie header={‘cookie‘:‘pgv_pvi=6636933120; RK=gRZhhBpNbS; ptcz=14bab564718e3e1048a09cc0e18a23f7c51f20d5b93da610cc1427f51f63a2f8; pgv_pvid=4990195883; ts_uid=5190463916; uin=o0511402865; pgv_si=s7505852416; skey=@2ttDS8Ljw; p_uin=o0511402865; pt4_token=AgqIsYBhO1b82zx1N4SxoGpCxGV0d38ss7jCI1nYfIg_; p_skey=9nlMjw4Uy44*Hu5iL3DOFonmAtZtExiniLykrsIRKmM_; traceid=14035c8a79‘} res = requests.post(url,data,headers=header) print(res.json())
4、上传文件
import requests # 上传文件 url = ‘http://api.nnzhp.cn/api/file/file_upload‘ f = open(‘lzh.jpg‘,‘rb‘) data = {‘file‘:f} res = requests.post(url,files=data) print(res.json()) f.close()
5、下载文件
import requests # 下载文件 requests.packages.urllib3.disable_warnings() url = ‘http://q4.qlogo.cn/g?b=qq&nk=1765242270&s=140‘ req = requests.get(url) f = open(‘lzh.jpg‘,‘wb‘) f.write(req.content) f.close()
6、传入json格式参数
import requests # 传入json格式?? url = ‘http://oapi.dingtalk.com/robot/send?access_token=5bff54100519897063cdb582989b3debe0f6529efd10731b38e48b7a74459f08‘ today = datetime.datetime.now() d = {"msgtype":"text","text":{"content":"lzh,现在是%s,大家不要忘记写作业哦"% today}} req = requests.post(url,json=d) print(req.json())
7、问题待解决
- requests.exceptions.SSLError???
以上是关于python-requests模块的主要内容,如果未能解决你的问题,请参考以下文章