python http请求利器Requests
只涉及一些常用的方法,一些高级特性查看尾部链接
安装
pip install requests
发送请求
#r 是response对象
r = requests.get('https://github.com/timeline.json')#get
r = requests.post("http://httpbin.org/post") #post
r = requests.put("http://httpbin.org/put") #put
r = requests.delete("http://httpbin.org/delete")#dele
r = requests.head("http://httpbin.org/get")#head
r = requests.options("http://httpbin.org/get")#options
响应内容的解析
r = requests.get('https://github.com/timeline.json')
r.text
#返回结果
#u'[{"repository":{"open_issues":0,"url":"https://github.com/...
二进制响应内容
r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
# 例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:
i = Image.open(BytesIO(r.content))
JSON 响应内容
r.json()
#返回内容
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
#
需要注意的是,成功调用 r.json() 并**不**意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同。
进阶
#get方法访问的时候的参数封装 可以使用一个字典类型封装参数
#这样的 http://httpbin.org/get?key2=value2&key1=value1
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
#也可以接受一个列表
#http://httpbin.org/get?key1=value1&key2=value2&key2=value3
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
带参数 post请求
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
#如果有请求的参数当中包含 json数组
payload = (('key1', 'value1'), ('key1', 'value2'))
请求体:
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
检测响应的状态码
r.status_code
#响应的异常抛出 code是200 则为none
r.raise_for_status()
设置超时时间 如果不设置超时时间则有可能会永远得不到返回
requests.get('http://github.com', timeout=0.001)