要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

 

# 带参数的get请求
r = requests.get('https://api.github.com/events', params = {'key1': 'value1', 'key2': 'value2'}) 

# 自定义headers 
r = requests.get('https://api.github.com/some/endpoint', headers={'user-agent': 'my-app/0.0.1'}) 

# 自定义cookies
r = requests.get('http://httpbin.org/cookies', cookies=dict(cookies_are='working'))   
r = requests.get(url, cookies=requests.cookies.RequestsCookieJar().set('tasty_cookie', 'yum', 
                                                                        domain='httpbin.org', 
                                                                        path='/cookies'))
#禁用重定向                                                                    
r = requests.get('http://github.com', allow_redirects=False) 
# 设置请求超时时间
r = requests.get('http://github.com', timeout=0.001)  


# 固定写法,post请求发表单数据,自动Content-Type=application/x-www-form-urlencoded
r = requests.post('http://httpbin.org/post', data = {'key':'value'})  
r = requests.post('http://httpbin.org/post', data=(('key1', 'value1'), ('key1', 'value2'))) #多个元素同一个key

# 固定写法,post发生json请求,自动Content-Type=application/json
r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))
r = requests.post('https://api.github.com/some/endpoint', json={'some': 'data'})

# 上传文件
r = requests.post('http://httpbin.org/post', files={'file': open('report.xls', 'rb')})  
r = requests.post(url, files={'file': ('report.xls', 
                                    open('report.xls', 'rb'), 
                                    'application/vnd.ms-excel', 
                                    {'Expires': '0'})})  # 显式地设置文件名,文件类型和请求头
# 其他请求
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')



r.status_code: 返回的状态码
r.url: 打印输出拼接后的URL
r.text:响应的body内容
r.encoding: 改变响应body的编码方式,r.text有乱码时改I
r.content: 二进制的响应body。content会自动解码 gzip 和deflate压缩
r.headers: 以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
r.json(): 响应的json内容
r.raw(): 原始套接字响应
r.cookies['example_cookie_name']: 访问响应中的cookies
r.history: requests默认自动重定向,可以看重定向的记录

 

 

 requests高级用法:http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

posted on 2018-11-22 18:30  要一直走下去  阅读(1242)  评论(0编辑  收藏  举报