requests的请求方式
import requests # 发送请求 r = requests.get(‘https://github.com/timeline.json‘) 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/get") r = requests.options("http://httpbin.org/get")
GET请求传递URL参数
你也许经常想为URL的查询字符串传递某种数据。当你手工构建URL时,数据会以键/值对的形式置于URL中,跟在一个问号的后面。
requests提供了params关键字来接收字典数据。
注意:字典值为None不会传入url中,字典值为列表值会分开传入URL中
payload={‘user‘:‘kong‘,‘pwd‘:None,‘email‘:[‘1@qq.com‘,‘2@qq.com‘]} r = requests.get(‘https://github.com/timeline.json‘,params=payload) print r.url
结果:
https://github.com/timeline.json?user=kong&email=1%40qq.com&email=2%40qq.com
响应内容
requests请求时,会解析http头部来推测文档对应的编码。当访问r.text时,会使用其来对文档内容进行解码,以字符形式返回数据,大多数 unicode 字符集都能被无缝地解码.
当然你也可以使用r.encoding来自定义编码.
import requests r = requests.get(‘https://github.com/timeline.json‘) print r.encoding r.encoding =‘ISO-8859-1‘ print r.text
二进制响应内容
我们可以通过r.content方式以字节的方式来获取响应体内容,request会自动为你解码gzip和deflate编码的响应数据。
from PIL import Image from io import BytesIO # 直接获取字节数据来生成图片 i = Image.open(BytesIO(r.content))
原文:http://www.cnblogs.com/kongzhagen/p/6231761.html