重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Requests库如何在Python中应用-创新互联

本篇文章给大家分享的是有关Requests库如何在Python中应用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联公司是一家专注于成都网站制作、网站设计与策划设计,万宁网站建设哪家好?成都创新互联公司做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:万宁等地区。万宁做网站价格咨询:13518219792

0 安装

pip install requests

1 发送请求

r=requests.get('https://www.baidu.com')
print r.status_code,r.text
r=requests.post('http://httpbin.org/post')
r=requests.put('http://httpbin.org/put')
r=requests.delete('http://httpbin.org/delete')
r=requests.head('http://httpbin.org/head')
r=requests.options('http://httpbin.org/')

2 发送get参数

param={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',params=param)

3 发送post参数

param={'key1':value1,'key2':value2}
r=requests.post('http://www.baidu.com/',params=param) #表单格式
r=requests.post('http://www.baidu.com/',json=param) #json格式数据
file= {'file':open('1.txt','rb')}
r=reuqest.post('http://httpbin.org/post',files=file)

4 文件下载

with open('1.pic','wb') as pic:
  for chunk in response.iter_content(size):
    pic.write(chunk)

5 携带header

header={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',headers=header)

6 携带cookie

cookie={'key1':value1,'key2':value2}
r=requests.get('http://www.baidu.com/',cookies=cookie)

7 重定向

默认requests是允许重定向的,并将重定向的历史保存在response.history数组中
如果不需要重定向,可以通过开关来关闭

r=requests.get('http://www.baidu.com/',allow_redirects=False)

8 使用代理

使用socks代理需要安装三方扩展包

pip install requests[socks]
proxy={
  'http':'http://127.0.0.1:8000',
  'https':'https://127.0.0.1:8080'
  'http':'socks5://user:pass@127.0.0.1:8132'
}
r=requests.get('https://www.github.com/',proxies=proxy)

9 设置连接超时

r=requests.get('http://www.baidu.com/',timeout=2.5)

10 ssl证书

证书验证

requests.get('https://kennethreitz.com', verify=True)
requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

如果指定本地证书及密钥,则密钥需要是解密的。

11 requests对象

r.url
r.text
r.headers

12 Response对象

response.request 对应的请求对象
response.raw socket上直接获得的数据
response.text 根据响应头进行解码的文本数据
response.content 不解码,返回二进制数据
response.json() 对返回数据进行json解码
response.headers 词典形式存储返回的headers
response.cookies 词典形式存储返回的cookies

以上就是Requests库如何在Python中应用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联成都网站设计公司行业资讯频道。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文题目:Requests库如何在Python中应用-创新互联
当前网址:http://cqcxhl.com/article/jppih.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP