Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求

一、安装 Requests

通过pip安装

Code example:

1

$ pip install requests

或者,下载代码后安装:

Code example:

1

2

3

$ git clone git://github.com/kennethreitz/requests.git

cd requests

$ python setup.py install

再懒一点,通过IDE安装吧,如pycharm!

二、发送请求与传递参数

先来一个简单的例子吧!让你了解下其威力:

Code example:

1

2

3

4

5

6

7

import requests

= requests.get(url='http://www.itwhy.org'# 最基本的GET请求

print(r.status_code) # 获取返回状态

= requests.get(url='http://dict.baidu.com/s', params={'wd':'python'}) #带参数的GET请求

print(r.url)

print(r.text) #打印解码后的返回数据

很简单吧!不但GET方法简单,其他方法都是统一的接口样式哦!

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请求

PS:以上的HTTP方法,对于WEB系统一般只支持 GET 和 POST,有一些还支持 HEAD 方法。
带参数的请求实例:

Code example:

1

2

3

import requests

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

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

POST发送JSON数据:

Code example:

1

2

3

4

5

import requests

import json

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

print(r.json())

定制header:

Code example:

1

2

3

4

5

6

7

8

9

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'}

= requests.post('https://api.github.com/some/endpoint', data=data, headers=headers)

print(r.text)

三、Response对象

使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……
获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。

Code example:

1

2

3

4

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

print(r.text, 'n{}n'.format('*'*79), r.encoding)

r.encoding = 'GBK'

print(r.text, 'n{}n'.format('*'*79), r.encoding)

其他响应:

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响应)抛出异常

案例之一:

Code example:

1

2

3

4

5

6

7

8

9

10

11

import requests

URL = 'http://ip.taobao.com/service/getIpInfo.php' # 淘宝IP地址库API

try:

= requests.get(URL, params={'ip''8.8.8.8'}, timeout=1)

r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常

except requests.RequestException as e:

print(e)

else:

result = r.json()

print(type(result), result, sep='n')

四、上传文件

使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理:

Code example:

1

2

3

4

5

6

7

8

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'))} #显式的设置文件名

= requests.post(url, files=files)

print(r.text)

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

Code example:

1

2

3

4

5

6

7

import requests

url = 'http://127.0.0.1:5000/upload'

files = {'file': ('test.txt', b'Hello Requests.')} #必需显式的设置文件名

= requests.post(url, files=files)

print(r.text)

五、身份验证

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

Code example:

1

2

3

4

5

6

import requests

from requests.auth import HTTPBasicAuth

= 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对它的支持也是开箱即可用的:

Code example:

1

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

六、Cookies与会话对象

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

Code example:

1

2

3

4

5

import requests

= requests.get('http://www.google.com.hk/')

print(r.cookies['NID'])

print(tuple(r.cookies))

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

Code example:

1

2

3

4

5

6

7

import requests

url = 'http://httpbin.org/cookies'

cookies = {'testCookies_1''Hello_Python3''testCookies_2''Hello_Requests'}

 

# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。

= requests.get(url, cookies=cookies)

print(r.json())

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

Code example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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'}

= requests.Session()

s.headers.update(headers)

# s.auth = ('superuser', '123')

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'})

= s.get(_URL, params={'ac':'zone''op':'taskdetail'})

print(r.json())

s.get(_URL, params={'ac':'common''op':'usersign'})

七、超时与异常

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

Code example:

1

2

3

4

>>> requests.get('http://github.com', timeout=0.001)

Traceback (most recent call last):

File "<stdin>", line 1in <module>

requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

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

Python 第三方 http 库-Requests 学习的更多相关文章

  1. 【转】Python 第三方 http 库-Requests 学习

    原文地址:http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/python/python-%E7%AC%AC%E4%B8%89%E6%9 ...

  2. Python关于PIL库的学习总结与成果展示

    一.关于PIL库的学习总结 PIL(Python Image Library)库是Python语言的第三方库,需要通过pip工具安装.安装PIL库的方法如下,需要注意,安装库的名字是pillow. : ...

  3. python 协程库gevent学习--gevent数据结构及实战(三)

    gevent学习系列第三章,前面两章分析了大量常用几个函数的源码以及实现原理.这一章重点偏向实战了,按照官方给出的gevent学习指南,我将依次分析官方给出的7个数据结构.以及给出几个相应使用他们的例 ...

  4. 新手学习Python第三方包库pip安装失败总结

    这篇文章纯原创,是之前自己学习使用pyhton时遇到的问题,故在此记录一下. 问题与需求:用python下载第三方库或包的时候出错怎么办? 方法有一下三种,可以解决大部分的问题. 1.在cmd命令控制 ...

  5. python第三方扩展库及不同类型的测试需安装相对应的第三方库总结

    如何安装第三方库 1.通过python的第三方仓库pypi中查找想要的第三方库 pypi地址:https://pypi.python.org/pypi pip是一个安装和管理Python包的工具,通过 ...

  6. python 协程库gevent学习--gevent数据结构及实战(四)

    一不留神已经到第四部分了,这一部分继续总结数据结构和常用的gevent类,废话不多说继续. 1.Timeout错误类 晚上在调试调用第三方接口的时候,发现有些接口耗时非常多,觉得应该有个超时接口来限制 ...

  7. python calendar标准库基础学习

    # -*- coding: utf-8 -*-# 作者:新手__author__ = 'Administrator'#标准库:日期时间基础学习:calendar:处理日期#例1import calen ...

  8. python 第三方扩展库的安装

    主要就是采用 easy_install 和pip安装,一定要把这两个东西安装好.http://peak.telecommunity.com/DevCenter/EasyInstall下载ez_setu ...

  9. 【人工智能系列】python的Quepy库的学习

    第一篇 了解 什么是Quepy quepy是一个Python框架改造自然语言问题在数据库查询语言查询.它可以很容易地定制不同类型的问题,在自然语言和数据库查询.因此,用很少的代码,你可以建立自己的系统 ...

随机推荐

  1. 【转】UGUI VS NGUI

    原文:http://gad.qq.com/college/articledetail/7191053 注[1]:该比较是基于15年-16年期间使用NGUI(3.8.0版本)与UGUI(4.6.9版本) ...

  2. 【bzoj4259/bzoj4503】残缺的字符串/两个串 FFT

    bzoj4259 题目描述 很久很久以前,在你刚刚学习字符串匹配的时候,有两个仅包含小写字母的字符串A和B,其中A串长度为m,B串长度为n.可当你现在再次碰到这两个串时,这两个串已经老化了,每个串都有 ...

  3. nodeJS学习(3)--- npm 配置和安装 express4.X 遇到的问题及解决

    前言:懒得看前面两篇介绍的也可以从本节直接参考,但建议最好了解下,因为 4.X 的express 已经把命令行工具分离出来 (链接https://github.com/expressjs/genera ...

  4. react 基础语法复习1- 搭建开发环境

    之前有看过阮一峰老师的react教程跟着做了一遍,学习了一下.好久没看,有点忘记了,这次跟着脚手架工具系统的复习一遍.顺便学习学习 react-router 和 redux 首先,脚手架工具我使用的是 ...

  5. 读扇区错误:0柱面0磁头1扇区(硬盘问题,蓝屏等 0x0000007B)

    原文发布时间为:2010-05-25 -- 来源于本人的百度文章 [由搬家工具导入] 读扇区错误:0柱面0磁头1扇区(硬盘问题,蓝屏等 0x0000007B) DISKGEN能找到,那就没什么大问题的 ...

  6. 【简单的原创】div简单轮换显示

    原文发布时间为:2009-05-10 -- 来源于本人的百度文章 [由搬家工具导入] <html><head><title>div简单轮换显示</title& ...

  7. Java反射获取类对象的三种方式

    package demo01; /* * 获取一个类的class文件对象的三种方式 * 1.对象获取 * 2.类名获取 * 3.Class类的静态方法获取 */ public class Reflec ...

  8. hdu3452 无向树去掉最小的边集使任何叶子与根不连通 / 最小割

    思路一下就上来了,叶子向汇点连边,inf保证不会成为割,跑根到汇点最小割即可.注意无向树双向建边.基础题,分分钟1A: #include<iostream> #include<que ...

  9. LeetCode OJ--4Sum *

    https://oj.leetcode.com/problems/4sum/ 在一个数列中,找出所有的4个数,它们的和是target. class Solution { public: vector& ...

  10. weblogic10.3.6忘记用户名或者密码的解决方法

    weblogic安装后,忘记访问控制台的用户名或者密码,可通过以下步骤来重置用户名密码. 版本:WebLogic Server 10.3 说明:%DOMAIN_HOME%:指WebLogic Serv ...