当前位置: 首页 > 后端技术 > Python

Requests:一个为人类设计的HTTP库

时间:2023-03-26 18:24:49 Python

简介Requests是一个优雅且易于使用的HTTP库。Requests的作者是KennethReitz。2019年,为了专注于requests3的开发,KennethReitz将requests2转移到PSF(PythonSoftwareFoundation)维护PyPI地址:https://pypi.org/project/requests/本文环境Windows10Python3.6.xRequests2.x安装pipinstallrequests-ihttps://mirrors.aliyun.com/pypi/simple/#socks5支持pipinstallrequests[socks]-ihttps://mirrors.aliyun.com/pypi/simple/proxies={'http':'socks5://127.0.0.1:1080','https':'socks5://127.0.0.1:1080'}使用示例cookierequests.utils.add_dict_to_cookiejar(cj,cookie_dict)sn.cookiesnolongerworkifsn.headers['Cookie']hasvalue.urllib3.disable_warnings(InsecureRequestWarning)高级用法python扩展包请求高级用法AdvancedUsage默认超时值socket.getdefaulttimeout()请求库使用最大超时值可以是放?geturl25%Requests的url中的百分号(%)在get时被强制编码为25%,可以通过以下方法解决:importrequestsn=requests.Session()url='http://xxx.净/xxx。aspx?Param=ASP.brief_result_aspx%23/%u5E74req=requests.Request('GET',url)prepped=sn.prepare_request(req)prepped.url=prepped.url.replace('%25','%')r=sn.send(prepped)orsplitandreassemble:importrequestsfromurllibimportparseurl='http://xxx.net/xxx.aspx?'+parse.urlencode(dict(parse.parse_qsl(parse.urlparse(url).query)))r=sn.get(url)POST请求POST表单重复键值处理dic={'key1':['aaa','bbb','ccc'],'key2':'xxx',}r=requests.post(url,data=dic)#这将被编码为:key1=aaa&key1=bbb&key1=ccc&key2=xxxaboutRequestPayload(发布一个多部分编码的文件)[code]importrequestsimportjsonr=requests.post('http://www.baidu.com',files={'key':'val'})print('***test1:%s'%r.request.body)print('------------------------')print(r.request.body.decode('utf8'))print('\n')line=json.dumps({'k1':'v1','k2':'v2'})r=requests.post('http://www.baidu.com',files={'json':(None,line)})print('***test2:%s'%r.request.body)print('------------------------')价格nt(r.request.body.decode('utf8'))【输出】***test1:b'--5b57f36c03ca462f93dfbd8dfc97e2d1\r\nContent-Disposition:form-data;名字=“钥匙”;filename="key"\r\n\r\nval\r\n--5b57f36c03ca462f93dfbd8dfc97e2d1--\r\n'---------------------------5b57f36c03ca462f93dfbd8dfc97e2d1Content-Disposition:表单数据;名字=“钥匙”;filename="key"val--5b57f36c03ca462f93dfbd8dfc97e2d1--***test2:b'--cf66a355e1f6441fa5a3079e1fafc43a\r\nContent-Disposition:form-data;name="json"\r\n\r\n{"k1":"v1","k2":"v2"}\r\n--cf66a355e1f6441fa5a3079e1fafc43a--\r\n'------------------------cf66a355e1f6441fa5a3079e1fafc43aContent-Disposition:表单数据;name="json"{"k1":"v1","k2":"v2"}--cf66a355e1f6441fa5a3079e1fafc43a--本文出自qbitsnap