一、发送请求与传递参数

简单demo:

import requests

r = requests.get(url='http://www.itwhy.org')    # 最基本的GET请求
print(r.status_code) # 获取返回状态
r = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'}) #带参数的GET请求
print(r.url)
print(r.text) #打印解码后的返回数据

1、带参数的请求

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参数实例

2、post发送json数据:

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

3、定制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对象

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

响应:

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

demo:

import requests

URL = 'http://ip.taobao.com/service/getIpInfo.php'  # 淘宝IP地址库API
try:
r = 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') # 结果:
# <class 'dict'>
# {'code': 0, 'data': {'ip': '8.8.8.8', 'country': '美国', 'area': '', 'region': 'XX', 'city': 'XX', 'county': 'XX', 'isp': 'Level3', 'country_id': 'US', 'area_id': '', 'region_id': 'xx', 'city_id': 'xx', 'county_id': 'xx', 'isp_id': '200053'}}

三、上传文件

1、上传文件

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)

2、可以把字符串当着文件进行上传:

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)

四、身份验证

1、基本身份认证(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())

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

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

五、Cookies与会话对象

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

import requests

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

2、要想发送你的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())

六、超时与异常

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)

七、实例demo

1、使用python第三方库requests,结合unittest、ddt数据驱动,实现get请求:使用多个搜索词,实现多条搜索case用例测试

import requests
import unittest
import ddt @ddt.ddt
class testClass(unittest.TestCase): @ddt.data("App专项测试", "自动化", "Python")
def testGet(self, queryword):
#header部分的配置
headers_data = {
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36',
'Host':'m.imooc.com',
'Referer': 'https://m.imooc.com/',
'Connection':'keep-alive', # 持续连接
'Accept-Encoding':'gzip, deflate, br'
} #cookies部分的配置
cookies_data = dict(imooc_uuid='f7356a8d-3dda-48b4-9a33-127b8f57e1db',
imooc_isnew_ct='',
imooc_isnew='',
page = 'https://m.imooc.com/') #get请求的构造
res = requests.get(
"https://m.imooc.com/search/?words="+queryword,
headers=headers_data,
cookies=cookies_data) #print res.status_code
#print res.text self.assertTrue("共找到" in res.text) if __name__ == "__main__":
unittest.main()

2、使用python第三方库requests,结合unittest、ddt数据驱动,实现post请求:使用多个账户密码,实现多个用户登录测试

import requests
import unittest
import ddt @ddt.ddt
class testClass(unittest.TestCase): @ddt.data(
("", ""),
("", "")
)
@ddt.unpack # 数据是元组或列表等格式,需要经过unpack解包后,再用于驱动实例
def testPost(self, username_data, password_data):
formdata = {
"username": username_data,
"password": password_data,
"verify": '',
"referer":'https://m.imooc.com'} headers_data = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36',
'Host': 'm.imooc.com'
} #cookies部分的配置
cookies_data = dict(imooc_uuid='ffbd103a-b800-4170-a267-4ea3b301ff06',
imooc_isnew_ct='',
imooc_isnew='',
page = 'https://m.imooc.com/') res = requests.post("https://m.imooc.com/passport/user/login",
data = formdata,
headers = headers_data,
cookies = cookies_data
) print(res.json()) # res是json_str格式,res.json():转化成字典格式
print(type(res.json()))
self.assertTrue(90003 == res.json()['status'] or 10005 == res.json()['status']) # 判断状态码是否是90003或10005 if __name__ == "__main__":
unittest.main()

运行结果:

G:\Python\selenium_test\Scripts\python.exe G:/Python/selenium_test/ddt_case/selenium_test.py
.{'status': 90003, 'msg': '验证码为空', 'data': []}
<class 'dict'>
{'status': 90003, 'msg': '验证码为空', 'data': []}
<class 'dict'>
.
----------------------------------------------------------------------
Ran 2 tests in 1.057s OK

备注:本文采集于:https://www.cnblogs.com/mrchige/p/6409444.html ,仅用于记录笔记学习!

python第三方库requests简单介绍的更多相关文章

  1. python第三方库requests详解

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

  2. python第三方库Requests的基本使用

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

  3. Python第三方模块--requests简单使用

    1.requests简介 requests是什么?python语言编写的,基于urllib的第三方模块 与urllib有什么关系?urllib是python的内置模块,比urllib更加简洁和方便使用 ...

  4. Python第三方库requests的编码问题

    PS:这个解决方法可能很简单,但是这是平时的一些细节问题,所以有必要提醒一下! 首先代码不多,就是通过get方法去获取豆瓣首页信息,如图:但是会报UnicodeEncodeError: 'gbk' c ...

  5. 爬虫 Http请求,urllib2获取数据,第三方库requests获取数据,BeautifulSoup处理数据,使用Chrome浏览器开发者工具显示检查网页源代码,json模块的dumps,loads,dump,load方法介绍

    爬虫 Http请求,urllib2获取数据,第三方库requests获取数据,BeautifulSoup处理数据,使用Chrome浏览器开发者工具显示检查网页源代码,json模块的dumps,load ...

  6. Python中第三方库Requests库的高级用法详解

    Python中第三方库Requests库的高级用法详解 虽然Python的标准库中urllib2模块已经包含了平常我们使用的大多数功能,但是它的API使用起来让人实在感觉不好.它已经不适合现在的时代, ...

  7. python爬虫:爬虫的简单介绍及requests模块的简单使用

    python爬虫:爬虫的简单介绍及requests模块的简单使用 一点点的建议: (学习爬虫前建议先去了解一下前端的知识,不要求很熟悉,差不多入门即可学习爬虫,如果有不了解的,我也会补充个一些小知识. ...

  8. 常用Python第三方库 简介

    如果说强大的标准库奠定了python发展的基石,丰富的第三方库则是python不断发展的保证,随着python的发展一些稳定的第三库被加入到了标准库里面,这里有6000多个第三方库的介绍:点这里或者访 ...

  9. 【Python基础】安装python第三方库

    pip命令行安装(推荐) 打开cmd命令行 安装需要的第三方库如:pip install numpy 在安装python的相关模块和库时,我们一般使用“pip install  模块名”或者“pyth ...

随机推荐

  1. 【JEECG技术文档】JEECG平台对外接口JWT应用文档V3.7.2

    一. 接口方式 接口调用采用http协议,rest请求方式: 二. 接口安全 接口安全采用Json web token (JWT)机制,基于token的鉴权机制. 1. 机制说明 基于token的鉴权 ...

  2. 文件操作 freopen函数

    转自http://blog.csdn.net/zhuyi2654715/article/details/6963673 当我们求解acm题目时,通常在设计好算法和程序后,要在调试环境(例如VC等)中运 ...

  3. Java如何创建参数个数不限的函数

    可变的参数类型,也称为不定参数类型.英文缩写是varargus,还原一下就是variable argument type.通过它的名字可以很直接地看出来,这个方法在接收参数的时候,个数是不定的. pu ...

  4. [Redis]Redis的快速配置使用(图)

    --------------------------------------------------------------------------------------------------- ...

  5. python 任务调度模块sched

    类似于crontab的功能,可以实现定时定点执行任务; 将已经生成的任务放入队列中,获取到了执行可以实现任务调度功能; 如果将需求复杂化,加上优先级策略,并能取消已经加入队列中的任务,就需要使用pyt ...

  6. IE (第二部分) 浏览器 中 关于浏览器模式和文本模式

    判断真正的 IE 版本 很多 JS 框架都通过 UA 判断 IE 的版本.对于 IE6,这种做法没问题( IE6 没有浏览器模式的概念,也没有其它 IE 可以把浏览器模式改为 IE6:IE7 虽然也没 ...

  7. Unity3D架构设计NavMesh寻路

    Unity3D架构设计NavMesh寻路 发表于2013年10月6日由陆泽西 国庆闲来没事把NavMesh巩固一下.以Unity3D引擎为例写一个底层c# NavMesh寻路.因为Unity3D中本身 ...

  8. 吴裕雄 08-MySQL创建数据表

    MySQL 创建数据表创建MySQL数据表需要以下信息:表名表字段名定义每个表字段 语法以下为创建MySQL数据表的SQL通用语法:CREATE TABLE table_name (column_na ...

  9. linux mysqlERROR 1045 (28000): linux忘记数据库密码

    已验证没问题 #1.停止mysql数据库(确定能停止掉,不然第二部有问题) /etc/init.d/mysqld stop   #2.执行如下命令 mysqld_safe --user=mysql - ...

  10. iptables禁止别人,允许自己

    这里举个例子,以ping为案例:禁止别人ping自己,但允许自己ping别人. [root@localhost ~]# iptables -A INPUT -p icmp --icmp-type 8 ...