原文的文件地址:http://blog.csdn.net/shanzhizi/article/details/50903748

一、安装 Requests

通过pip安装

pip install requests

或者,下载代码后安装:

$ git clone git://github.com/kennethreitz/requests.git $ cd requests $ python setup.py install

基本的语法:

支持的 请求:

requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求

GET请求:

import requests
requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #GET参数实例 params={'wd': 'python'}可参数话 :
--------------------------------------------------- payload={'wd': 'python'} import requests
requests.get('http://www.dict.baidu.com/s', params=payload)

 ————————————————————----------

POST请求:


import requests

requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '测试POST'})    #POST参数实例

 

-------------------------------------

POST发送JSON数据:


import requests
import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))
print(r.json())

 

定制header:

import requests
import json data = {'some': 'data'}
headers = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)
print(r.text)

Response对象:

r = requests.get('http://www.itwhy.org')

r.status_code #响应状态码
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
#*特殊方法*#
r.json() #Requests中内置的JSON解码器
r.raise_for_status() #失败请求(非200响应)抛出异常

上传文件

import requests

url = 'http://127.0.0.1:5000/upload'
files = {'file': open('/home/lyb/sjzl.mpg', 'rb')}
#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))} #显式的设置文件名 r = requests.post(url, files=files)
print(r.text)

更加方便的是,你可以把字符串当着文件进行上传:

import requests

url = 'http://127.0.0.1:5000/upload'
files = {'file': ('test.txt', b'Hello Requests.')} #必需显式的设置文件名 r = requests.post(url, files=files)
print(r.text)

身份验证

基本身份认证(HTTP Basic Auth):

import requests
from requests.auth import HTTPBasicAuth r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) # 简写
print(r.json())

另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:

requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))

Cookies与会话对象

如果某个响应中包含一些Cookie,你可以快速访问它们:

import requests

r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))

要想发送你的cookies到服务器,可以使用 cookies 参数:

import requests

url = 'http://httpbin.org/cookies'
cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。
r = requests.get(url, cookies=cookies)
print(r.json())

会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。
下面就来一个真正的实例,如下是快盘签到脚本:

import requests

headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, compress',
'Accept-Language': 'en-us;q=0.5,en;q=0.3',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} s = requests.Session()
s.headers.update(headers)
# s.auth = ('superuser', '')
s.get('https://www.kuaipan.cn/account_login.htm') _URL = 'http://www.kuaipan.cn/index.php'
s.post(_URL, params={'ac':'account', 'op':'login'},
data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})
r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'})
print(r.json())
s.get(_URL, params={'ac':'common', 'op':'usersign'})

超时与异常

timeout 仅对连接过程有效,与响应体的下载无关。

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。

python3 中 requests 框架的更多相关文章

  1. Python3中requests库学习01(常见请求示例)

    1.请求携带参数的方式1.带数据的post data=字典对象2.带header的post headers=字典对象3.带json的post json=json对象4.带参数的post params= ...

  2. python3中Requests将verify设置为False后,取消警告的方式

    import requests resp = requests.get('https://www.***.com', verify=False) 调用成功但是会有如下警告信息: InsecureReq ...

  3. 详解:Python2中的urllib、urllib2与Python3中的urllib以及第三方模块requests

    在python2中,urllib和urllib2都是接受URL请求的相关模块,但是提供了不同的功能.两个最显著的不同如下: 1.urllib2可以接受一个Request类的实例来设置URL请求的hea ...

  4. Python3中性能测试工具Locust安装使用

    Locust安装使用: 安装: python3中           ---> pip3 install locust 验证是否安装成功---> 终端中输入 locust --help  ...

  5. python3使用requests登录人人影视网站

    python3使用requests登录人人影视网站 继续练习使用requests登录网站,人人影视有一项功能是签到功能,需要每天登录签到才能升级. 下面的代码python代码实现了使用requests ...

  6. python3使用requests发闪存

    闪存ing.cnblogs.com是博客园类似推特.饭否的服务, 我写了以下程序可以完成发闪存的操作,目的是顺便练习使用requests库. requests是一个python 轻量的http客户端库 ...

  7. Python3.6 性能测试框架Locust的搭建与使用

    背景 Python3.6 性能测试框架Locust的搭建与使用 基础 python版本:python3.6 方法一: pip install locustio 方法二: 开发工具:pycharm 使用 ...

  8. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  9. Python3下requests库发送multipart/form-data类型请求

    [本文出自天外归云的博客园] 要模拟multipart/form-data类型请求,可以用python3的requests库完成.代码示例如下: #请求的接口url url = "url&q ...

随机推荐

  1. JNI_C#

    1. 基本就是 通过 JAVA --> C/C++ --> C#的DLL 2. (1).自己写 JNI与 C#的DLL 通信 http://www.cnblogs.com/yinhaimi ...

  2. 被人遗忘的MAX_FILE_SIZE文件上传限制大小参数

    在文件上传中,我们经常会要求显 示用户上传文件大小,超过上传限制的文件就会不允许用户上传.虽然我们可以用程序去判断上传文件是否超过限制,但是其实我们的PHP程序是无法判断用户本 地文件大小的.所以等到 ...

  3. MSDN 单机 MVC 帮助文档

    因为微软的mvc框架也是从开源框架演变而来的,所以微软没把mvc帮助文档放到单击帮助文档中.sososos下载好msdn单机帮助后,却找不到 System.Web.MVC 等命名空间的东西. 解决办法 ...

  4. C语言基础二

    C--顺序程序设计 赋值语句 赋值语句和赋值表达式的区别: if((a = b) > 0) t = 0; 字符数据的输入输出 putchar函数 该函数为字符输出函数,其作用是向终端数出一个字符 ...

  5. MinGW main()

    MinGW没有wmain入口函数,为了获取宽字符的参数,可以用系统API函数GetCommandLineW. main.cpp #include <iostream> #include & ...

  6. JVM 知识点总览 - 高级 Java 工程师面试必备

    在江湖中要练就绝世武功必须内外兼备,精妙的招式和深厚的内功,武功的基础是内功.对于武功低(就像江南七怪)的人,招式更重要,因为他们不能靠内功直接去伤人,只能靠招式,利刃上优势来取胜了,但是练到高手之后 ...

  7. hzau 1207 Candies

    1207: Candies Time Limit: 2 Sec  Memory Limit: 1280 MBSubmit: 223  Solved: 31[Submit][Status][Web Bo ...

  8. 51nod 1428 贪心

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1428 1428 活动安排问题 基准时间限制:1 秒 空间限制:13107 ...

  9. 【Prism】MEF版EventAggregation

    引言 第三弹是EventAggregation Demo的改造. EventAggregation  EventAggregation事件聚集是Prism框架中的通信实现.它可以在松散的模块或者窗体之 ...

  10. 浪漫爱心--第三方开源--PeriscopeLayout

    点此下载 使用很简单,首先在xml里面添加 <Button android:id="@+id/btn_start" android:layout_width="wr ...