一、发送请求与传递参数

简单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. 机器学习入门-数值特征-进行二值化变化 1.Binarizer(进行数据的二值化操作)

    函数说明: 1. Binarizer(threshold=0.9) 将数据进行二值化,threshold表示大于0.9的数据为1,小于0.9的数据为0 对于一些数值型的特征:存在0还有其他的一些数 二 ...

  2. Oracle 学习总结 - 问题诊断

    搜集常用诊断sql https://blog.csdn.net/yangshangwei/article/details/52449489 lock相关: 1. 查看lock, 打开两个事物,事物1更 ...

  3. js 提示框的实现---组件开发之(一)

    自己做了一个简单的提示框,供自己使用,也可以供他人参考,看懂此文,是理解组件开发的入门 思路比较简单: 1.常规写法: 1.1. 创建一个构造函数 1.2. 给构造函数的原型对象添加show 和hid ...

  4. java后端实习生面试题目

    1.编程题:java从10000到99999找到AABB类型 public class Test1 { public static void main(String[] args) { String ...

  5. PHP搜索中的sql注入

    ----------------------------------------------------------------------------------------- 防止查询的sql攻击 ...

  6. Python模块和类.md

    模块的定义 代码的层次结构 对于python的层次结构一般为包->模块 包也就是文件夹,但是文件夹下必须有文件"init.py"那么此文件夹才可以被识别为包."in ...

  7. android事件处理概括

    什么是事件处理? 事件处理就是针对用户的一些特定操作,进行相对应的回馈.时间处理也是程序开发中的人机交互的一个非常重要的体现.事件处理中,事件源是事件的起始位. 一.事件处理三要素 事件源——事件—— ...

  8. MongoDB模糊查询,以及MongoDB模糊查询时带有括号的情况

    模糊查询 记录如下: { "_id" : ObjectId("5c3d486d24aa9a000526367b"), "name" : &q ...

  9. Java文件上传:Restful接口接收上传文件,缓存在本地

    接口代码 import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; i ...

  10. js高级-闭包

    function foo(x){ var tmp = 3; return function(y){ //把一个函数作为返回值,定义时候的作用域 console.log(x+y+(++tmp)) //+ ...