程序猿阵线联盟-汇总各类技术干货Python 大数据 爬虫 学习成为程序员python爬虫

Requests模块三分钟掌握用法!

2018-06-13  本文已影响3人  f4698891a569
简介

Feature Support:

International Domains and URLs —— 国际化域名和URL

Keep-Alive & Connection Pooling —— Keep-Alive & 连接池

Sessions with Cookie Persistence —— 带持久Cookie的会话

Browser-style SSL Verification —— 浏览器式的SSL认证

Basic/Digest Authentication —— 基本/摘要式的身份认证

Elegant Key/Value Cookies —— 优雅的 key/value Cookie

Automatic Decompression —— 自动解压

Automatic Content Decoding —— 自动内容解码

Unicode Response Bodies —— Unicode响应体

Multipart File Uploads —— 文件分块上传

HTTP(S) Proxy Support —— HTTP(S)代理支持

Connection Timeouts —— 连接超时

Streaming Downloads —— 流下载

.netrc Support —— 支持.netrc

Chunked Requests —— Chunked请求

有些听都听不懂,感觉很牛逼的样子

先通过 pip install request 安装一波库,然后就可以开始玩了!

三分钟上手requests

1.支持各种请求方式:GET,POST,PUT,DELETE,HEAD,OPTION

r1 = requests.get("http://xxx", params={"x": 1, "y": 2})

r2 = requests.post("http://xxx", data={"x": 1, "y": 2})

r3 = requests.put("http://xxx")

r4 = requests.delete("http://xxx")

r5 = requests.head("http://xxx")

r6 = requests.options("http://xxx")

想要学习 Python的可以加群:725479218

注意:

URL链接里有中文会自动转码

post时如果传递的是一个str而不是一个dict,会直接发送出去!(比如json字符串)

2.4.2版新增:可以通过json参数传递dict,自动会把dict转换为json字符串!

post上传文件可以通过file参数,如post(url, files={‘file’: open(‘report.xls’, ‘rb’)})

请求的相关设置:

请求头:headers={‘xxx’:’yyy’}

代理:proxies={‘https’:’xxx’}

超时(单位秒):timeout=15

处理返回结果

注:由requests发起的请求,当相应内容经过gzip或deflate压缩时,

requests会自动解包,可以获得通过content获得byte方式的响应结果。

status_code:获取状态码

reason:状态信息

url:获取请求的url

content: 获取byte类型的返回结果,相当于urllib.urlopen().read;

raw:获得原始的返回结果,请求里需要设置stream=True;

text:获取str类型的返回结果,会自动根据响应头部的字符编码进行解码;

可以调用r.encoding获得编码方式,或者在调text之前先r.encoding=’编码’

想要学习 Python的可以加群:725479218

设置编码类型,text就会按照对应的编码进行解析;

json:解析序列化为JSON格式的数据,直接就可以[‘xxx’]拿数据了,

如果解析错误会抛出异常:ValueError: No JSON object could be decoded

除此之外还可以调用headers获得响应头比如:

r = requests.get('http://gank.io/api/data/福利/50/1')

直接根据键获得值

print(r.headers.get('Date'))

遍历获得请求头里所有键值

for key, value in r.headers.items():

print(key + " : " + value)
上一篇下一篇

猜你喜欢

热点阅读