安装:

pip install requests

使用:

import requests

HTTP请求:GET、POST、PUT、DELETE、HEAD、OPTIONS

1) get

res = requests.get("https://github.com/timeline.json")

2) post

res = requests.post("http://httpbin.org/post");

3) put

res = requests.put("http://httpbin.org/put");

4) delete

res = requests.delete("http://httpbin.org/delete");

5) head

res = requests.head("http://httpbin.org/get") ;

6) options

res = requests.options("http://httpbin.org/get")

为URL传递参数

requests模块使用params关键字参数,以一个字典的形式来提供参数。

  1. >>> payload = {'key1':'value','key2':'value2'}
  2. >>> res = requests.get("http://httpbin.org/get",params=payload)
  3. >>> res.url
  4. u'http://httpbin.org/get?key2=value2&key1=value'

查看响应内容

  1.     >>> res = requests.get("http://github.org/timeline.json")
  2.     >>> res.text
  3.     u'{"message":"Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}'

requests模块会自动解码来自服务器的内容,可以使用res.encoding来查看编码,在你需要的情况下,request也可以使用定制的编码,并使用codes模块进行注册,这样你就可以轻松的使用这个解码器的名称作为res.encoding的值

  1.      >>> res.encoding
  2.     'utf-8'
  3.      >>> res.encoding = "gbk2312"

以json格式获取响应的内容

  1.     >>> res = requests.get("http://github.org/timeline.json")  
  2.     >>> res.json()
  3. {u'documentation_url': u'https://developer.github.com/v3/activity/events/#list-public-events', u'message': u'Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.'}

原始的应该内容

  1.     >>> res = requests.get("http://github.org/timeline.json")
  2.     >>> res.raw
  3.     <requests.packages.urllib3.response.HTTPResponse object at 0x0000000002F31550>
  4.     >>> res.raw.read(10)
  5.     ''

定制请求头

  1.     >>> import json
  2.     >>> url = 'https://api.github.com/some/endpoint'
  3.     >>> payload = {'some': 'data'}
  4.     >>> headers = {'content-type': 'application/json'}
  1. post请求参数是这样:
  1. >>> payload = {'key1':'value1','key2':'value2'}
  2. >>> url = "http://httpbin.org/post"
  3. >>> res =requests.post(url,data=payload)
  4. >>> res.text
  5. u'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "key1": "value1", \n    "key2": "value2"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "23", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.10.0"\n  }, \n  "json": null, \n  "origin": "218.240.129.20", \n  "url": "http://httpbin.org/post"\n}\n'
  6. >>> print res.text
  7. {
  8.   "args": {}, 
  9.   "data": "", 
  10.   "files": {}, 
  11.   "form": {
  12.     "key1": "value1", 
  13.     "key2": "value2"
  14.   }, 
  15.   "headers": {
  16.     "Accept": "*/*", 
  17.     "Accept-Encoding": "gzip, deflate", 
  18.     "Content-Length": "", 
  19.     "Content-Type": "application/x-www-form-urlencoded", 
  20.     "Host": "httpbin.org", 
  21.     "User-Agent": "python-requests/2.10.0"
  22.   }, 
  23.   "json": null, 
  24.   "origin": "218.240.129.20", 
  25.   "url": "http://httpbin.org/post"
  26. }

响应状态码及响应头:

>>> res = requests.get("http://httpbin.org/get")

  1. >>> res.status_code
  2. 200
  3. >>> res.status_code == requests.codes.ok
  4. True
  5. >>> res.headers
  6. {'Content-Length': '', 'Server': 'nginx', 'Connection': 'keep-alive', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Sun, 22 May 2016 09:24:10 GMT', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}
  7. >>> print res.headers
  8. {'Content-Length': '', 'Server': 'nginx', 'Connection': 'keep-alive', 'Access-Control-Allow-Credentials': 'true', 'Date': 'Sun, 22 May 2016 09:24:10 GMT', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'}
  9. >>> res.headers['Content-Type']
  10. 'application/json'
  11. >>> res.headers.get('content-type')
  12. 'application/json'
  13. >>> res.headers.get('Connection')
  14. 'keep-alive'
  15. >>> 

Cookies:

访问cookies

  1. >>> url = 'http://example.com/some/cookie/setting/url'
  2. >>> r = requests.get(url)

>>> r.cookies['example_cookie_name']

设置cookies

  1. >>> url = 'http://httpbin.org/cookies'
  2. >>> cookies = dict(cookies_are='working')
  3.  
  4. >>> r = requests.get(url, cookies=cookies)
  5. >>> r.text

'{"cookies": {"cookies_are": "working"}}'

python request模块学习的更多相关文章

  1. python - argparse 模块学习

    python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...

  2. python paramiko模块学习分享

    python paramiko模块学习分享 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接.paramiko支持Linux, Sola ...

  3. Python logging 模块学习

    logging example Level When it's used Numeric value DEBUG Detailed information, typically of interest ...

  4. Python time模块学习

    Python time模块提供了一些用于管理时间和日期的C库函数,由于它绑定到底层C实现,因此一些细节会基于具体的平台. 一.壁挂钟时间 1.time() time模块的核心函数time(),它返回纪 ...

  5. python os模块学习

    一.os模块概述 Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的. 二.常用方法 1.os.name 输出字符串指示正在使用的平台.如果是wi ...

  6. python logging模块学习(转)

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  7. python atexit模块学习

    python atexit模块 只定义了一个register模块用于注册程序退出时的回调函数,我们可以在这个函数中做一下资源清理的操作 注:如果程序是非正常crash,或者通过os._exit()退出 ...

  8. Python 第二模块学习总结

    学习总结: 1.掌握对装饰器的用法 2.掌握生成器的用法 3.掌握迭代器的用法 4.熟悉Python内置函数 5.熟悉Python shutil/shelve/configparse/hashlib/ ...

  9. Python requests模块学习笔记

    目录 Requests模块说明 Requests模块安装 Requests模块简单入门 Requests示例 参考文档   1.Requests模块说明 Requests 是使用 Apache2 Li ...

随机推荐

  1. Http请求头中的字段理解

    1.Accept属于请求头, Content-Type属于实体头. Http报头分为通用报头,请求报头,响应报头和实体报头. 请求方的http报头结构:通用报头|请求报头|实体报头 响应方的http报 ...

  2. ES6笔记② 箭头函数

    特性介绍 箭头函数是ES6新增的特性之一,它为JS这门语言提供了一种全新的书写函数的语法. //ES5 function fun(x,y){ return x+y; } console.log(fun ...

  3. 2016-09-06 J2EE基础知识之不知

    1.中间件.容器.Web服务器 1.1中间件 中间件是提供系统软件和应用软件之间连接的软件,以便于软件各部件之间的沟通.中间件处于操作系统和更高一级应用程序之间. J2EE提出的背景: 1)企业级应用 ...

  4. jquery 获取当前元素的索引值

    $("#lisa > li").mouseover(function(){ alert($("#lisa > li").length); alert ...

  5. mysql自定义循环函数

    FUNCTION deyes.f_getSplitStringByIndex1_8(stringIn text, delimiter varchar(10), indexIn int) RETURNS ...

  6. 页面类跳转Demo

    package baidumapsdk.demo; import android.app.Activity; import android.content.BroadcastReceiver; imp ...

  7. ASP.NET MVC3使用Unity2.0实现依赖注入(转载和扩展)

    http://note.youdao.com/share/?id=53252d0f897e0e109aadd296a1682354&type=note

  8. WPF的重要新概念

    原文 http://www.cnblogs.com/free722/archive/2011/11/12/2238654.html 逻辑树与可视树 XAML天生就是用来呈现用户界面的,这是由于它具有层 ...

  9. Xcode 真机测试破解方法(转加修改)xcode 4.3 通过

    Xcode 真机测试破解方法(转加修改)xcode 4.3 通过 生成本机证书 应用程序->实用工具->钥匙串访问 菜单:钥匙串访问->证书助理->创建证书, 然后按以下图片顺 ...

  10. poj2365---求多边形边长总和

    #include <stdio.h> #include <stdlib.h> #include<math.h> #define pi acos(-1) struct ...