python Requests 初级

一、介绍

Requests 是用Python语言编写,基于 urllib,但是它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 !

二、用法

1、使用 Requests 发送网络请求

import requests

r = requests.get(‘https://github.com/timeline.json‘)

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

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

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

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

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

2、传递 URL 参数

payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}

r = requests.get("http://httpbin.org/get", params=payload)

通过打印输出该 URL,你能看到 URL 已被正确编码:

print(r.url)

http://httpbin.org/get?key2=value2&key1=value1

3、响应内容

r.text可以看到地址响应的内容

Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

4、二进制响应内容

你也能以字节的方式访问请求响应体

r.content

Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。

例:以请求返回的二进制数据创建一张图片:

from PIL import Image

from io import BytesIO

i = Image.open(BytesIO(r.content))

5、JSON 响应内容

Requests 中也有一个内置的 JSON 解码器

import requests

r = requests.get(‘https://github.com/timeline.json‘)

r.json() 如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问                       r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

6、定制请求头

url = ‘https://api.github.com/some/endpoint‘

headers = {‘user-agent‘: ‘my-app/0.0.1‘}

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

所有的 header 值必须是 string、bytestring 或者 unicode。

7、更加复杂的 POST 请求

payload = ((‘key1‘, ‘value1‘), (‘key1‘, ‘value2‘))

r = requests.post(‘http://httpbin.org/post‘, data=payload)

print(r.text)

(json直接传递)

import json

url = ‘https://api.github.com/some/endpoint‘

payload = {‘some‘: ‘data‘}

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

8、响应状态码

r.status_code(状态码)

r.raise_for_status()   (抛出异常)

9、响应头

r.headers

10、Cookie

url = ‘http://example.com/some/cookie/setting/url‘

r = requests.get(url)

r.cookies[‘example_cookie_name‘]

‘example_cookie_value‘

发送你的cookies到服务器:(Cookie 的返回对象为 RequestsCookieJar)

r = ‘http://httpbin.org/cookies‘

cookies = dict(cookies_are=‘working‘)

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

r.text

‘{"cookies": {"cookies_are": "working"}}‘

11、重定向与请求历史

默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。

Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

例:Github 将所有的 HTTP 请求重定向到 HTTPS:

r = requests.get(‘http://github.com‘)

r.url

‘https://github.com/‘

r.status_code

200

r.history

[<Response [301]>]

可以通过 allow_redirects 参数禁用重定向处理:

r = requests.get(‘http://github.com‘, allow_redirects=False)

r.status_code

301

r.history

[]

12、超时

你可以告诉 requests在经过以timeout参数设定的秒数时间之后停止等待响应。如果不使用,你的程序可能会永远失去响应:

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

注意:

timeout仅对连接过程有效,与响应体的下载无关。timeout并不是整个下载响应的时间限制,而是如果服务器在timeout秒内没有应答,将会引发一个异常。

13、错误与异常

遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。

如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

时间: 2024-08-29 04:49:47

python Requests 初级的相关文章

Python+Requests接口测试教程(1):Fiddler抓包工具

本书涵盖内容:fiddler.http协议.json.requests+unittest+报告.bs4.数据相关(mysql/oracle/logging)等内容.刚买须知:本书是针对零基础入门接口测试和python+requests自动化的,首先本书确实写的比较基础,对基础内容也写的很详细,所以大神绕道. 为什么要先学fiddler? 学习接口测试必学http协议,如果直接先讲协议,我估计小伙伴们更懵,为了更好的理解协议,先从抓包开始.结合抓包工具讲http协议更容易学一些. 1.1 抓fir

Python requests

Python requests备忘 0x01 1 #coding:utf-8 2 import requests 3 4 res = requests.get('http://www.baidu.com') 5 print res.status_code 6 print res.headers['content-type'] #头部信息 7 print res.encoding #编码信息 8 print res.text9 print res.content 0x02 payload 1 im

Python requests 自动登录某财BBS,自动签到打卡领铜钱,最后再配个plist,每天自动执行

某财的用户应该都知道这个网站,在"签到有礼"版块,每天会有一贴,用帖子中给出的关键字回帖,得铜钱,据说铜钱可以换现金,还可以换书. 真好,裸辞在家的失业人员最需要这个-每天领之. 基本思路: 先用抓包工具仔细分析下登陆以及回帖时post了哪些数据,这些数据从何而来(我用的Firefox + Firebug,挺好用的,选上保持+全部,就算页面重定向,所有的请求也都能看到): python requests库,用requests.Session().post来登陆和回帖,用get来读取页面

大概看了一天python request源码。写下python requests库发送 get,post请求大概过程。

python requests库发送请求时,比如get请求,大概过程. 一.发起get请求过程:调用requests.get(url,**kwargs)-->request('get', url, **kwargs)-->session.request(method="get", url=url, **kwargs)-->session.send(request, **kwargs)-->adapter.send(request, **kwargs)-->

Python+Requests编码识别Bug

Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,更友好,更易用. Requests 使用的是 urllib3,因此继承了它的所有特性.Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码.现代.国际化.人性化. 最近在使用Requests的过程中发现一个问题,就是抓去某些中文网页的时候,出现乱码,打印encodin

python requests库学习笔记(上)

尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.python-requests.org/zh_CN/latest/: requests库作者Kenneth Reitz个人主页:https://www.kennethreitz.org/: requests库github地址:https://github.com/requests/requests: requ

Python Requests 小技巧总结

关于 Python Requests ,在使用中,总结了一些小技巧把,分享下. 1:保持请求之间的Cookies,我们可以这样做. import requests self.session = requests.Session() self.session.get(login_url) # 可以保持登录态 2:请求时,会加上headers,一般我们会写成这样 self.session.get(url, params, headers=headers) 唯一不便的是之后的代码每次都需要这么写,代码

基于Python Requests的数据驱动的HTTP接口测试

发表于:2017-8-30 11:56  作者:顾翔   来源:51Testing软件测试网原创 http://www.51testing.com/html/69/n-3720769-2.html 1.测试金字塔 图 1软件测试金字塔 图 1是Main Cohn提出的软件测试金字塔,他认为作为一个测试工程师应该把大量的工作花在单元测试和接口测试,而其余的发在UI测试以及探索式测试.纵然,单元测试的优点很突出,它接近于代码本身,运行速度快,开发可以一边写产品代码一边写单元测试代码,一旦在单元测试中

Python requests jira登录302重定向

总结一下自己在用Python requests库对jira进行的一个bug统计时,在登录遇到的问题,以前也遇到过登录302重定向的问题,那个时候用requests同样的方法没有获取到cookie,但是jira可以用requests获取到cookie,我也不知道怎么回事 网上百度了很多资料,好多都是用jira这个库来来统计的,但是我想自己用Python来写一下,以下做个记录, 1,首先了解一下接口登录大概的信息,看看jira登录时抓包的情况,我用的是谷歌F12 login.jsp接口详情如下,经试