python接口自动化-requests库

requests库

requests快速上手
http://2.python-requests.org/zh_CN/latest/user/quickstart.html
官方文档:https://requests.readthedocs.io/projects/cn/zh-cn/latest/

Requests库是用来发送HTTP请求,接收HTTP响应的一个Python库。
Requests库经常被用来 爬取 网站信息。用它发起HTTP请求到网站,从HTTP响应消息中提取信息。
Requests库也经常被用来做 网络服务系统的Web API 接口测试。因为Web API 接口的消息基本上都是通过HTTP协议传输的。
Python中构建HTTP请求的库有很多,其中 Requests 库最为广泛使用,因为它使用简便,功能强大。
Requests库不是Python标准库,而是第三方开发的。所以需要我们安装一下:

pip install requests

requests库常用方法:

requests.requests()剩下六种方法都是由requests()方法实现的,因此我们也可以说requests()方法是最基本的
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请求

传递参数

payload = {‘key1’: ‘value1’, ‘key2’: [‘value2’, ‘value3’]}

r = requests.get(‘http://httpbin.org/get’, params=payload)
params: 字典或者字节序列,作为参数增加到url中

定制请求头

如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了。

例如,在前一个示例中我们没有指定 content-type:

url = ‘https://api.github.com/some/endpoint’
headers = {‘user-agent’: ‘my-app/0.0.1’}

r = requests.get(url, headers=headers)

POST 请求

需简单地传递一个字典给 data 参数,数据字典在发出请求时会自动编码为表单形式:
如果你传递一个 string 而不是一个 dict,那么数据会被直接发布出去。
除了可以自行对 dict 进行编码,你还可以使用 json 参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能:

url = ‘https://api.github.com/some/endpoint’
payload = {‘some’: ‘data’}

r = requests.post(url, json=payload)

cookies: 字典或CookieJar, Requests中的cookie

files: 字典类型,传输文件

使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,

响应内容:

r.status_code 响应状态码

HTTP响应状态码,200表示响应成功,404表示失败
我们可以检测响应状态码:

r = requests.get(‘http://httpbin.org/get’)
r.status_code
200

如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:

bad_r = requests.get(‘http://httpbin.org/status/404’)
bad_r.status_code
404

bad_r.raise_for_status()
Traceback (most recent call last):
File “requests/models.py”, line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error

r.content #以字节的方式访问请求响应体,对于非文本请求

r.text #字符串方式的响应体,

r.headers 响应头

r.json() #字典方式的响应体

Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:

import requests

r = requests.get(‘https://api.github.com/events’)
r.json()
[{u’repository’: {u’open_issues’: 0, u’url’: 'https://github.com/…

cookie

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

url = ‘http://example.com/some/cookie/setting/url’
r = requests.get(url)

r.cookies[‘example_cookie_name’]
‘example_cookie_value’
要想发送你的cookies到服务器,可以使用 cookies 参数:

url = ‘http://httpbin.org/cookies’
cookies = dict(cookies_are=‘working’)

r = requests.get(url, cookies=cookies)
r.text
‘{“cookies”: {“cookies_are”: “working”}}’

超时

超时¶
你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:

requests.get(‘http://github.com’, timeout=0.001)
Traceback (most recent call last):
File “”, line 1, in
requests.exceptions.Timeout: HTTPConnectionPool(host=‘github.com’, port=80): Request timed out. (timeout=0.001)

会话对象

会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie
会话对象具有主要的 Requests API 的所有方法。

我们来跨请求保持一些 cookie:

s = requests.Session()

s.get(‘http://httpbin.org/cookies/set/sessioncookie/123456789’)
r = s.get(“http://httpbin.org/cookies”)

print(r.text)
'{“cookies”: {“sessioncookie”: “123456789”}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值