一、发送请求与传递参数

简单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. Delphi 使用MD5 比对文件

    使用MD5的方法比对CXimage里图片是否改变: Delphi7实现方法: uses IdHashMessageDigest function TForm1.GetImageMD5(cxImage: ...

  2. How to Pronounce the Word ARE

    How to Pronounce the Word ARE Share Tweet Share Tagged With: ARE Reduction Study the ARE reduction. ...

  3. MySQL中tinytext、text、mediumtext和longtext详解【转】

    一.数字类型 类型 范围 说明   Char(N) [binary] N=1~255 个字元binary :分辨大小写 固定长度 std_name cahr(32) not null VarChar( ...

  4. Delphi的子类化控件消息, 消息子类化

    所谓的子类化,网上有很多说明,我就说我个人的随意理解,可能有误,请列位看官斟酌理解. 所谓子类化,个人理解就是拦截某个控件的消息以及样式,来进行自己的特定处理以达到特殊的功能需求.这个子类化,可以有子 ...

  5. C# Liseview的使用方法之一:滚动到选中的行

    listview.items[i].EnsureVisible();//滚动到你想要显示出来的行上. 其中,listview.items[i]就是你想要显示的行.

  6. javascript:getElementsByName td name

    问题:    今天写动态生成HTML表格的时候需要用到统计td内的数据,在生成的时候设置了td的name属性,但是document.getElementsByName("tdname&quo ...

  7. ubuntu 下安装和启动SSH 服务

    安装OPENSSH 服务端 sudo apt-get install openssh-server 查看进程是否启动 ps -e | grep ssh 删除密钥文件 rm /etc/ssh/ssh_h ...

  8. 认识 Thymeleaf

  9. Docker 指定容量

    vim /etc/sysconfig/docker-storage加入以下命令 DOCKER_STORAGE_OPTIONS="--storage-driver devicemapper - ...

  10. Oracle SCN机制解析

    SCN(System Chang Number)作为oracle中的一个重要机制,在数据恢复.Data Guard.Streams复制.RAC节点间的同步等各个功能中起着重要作用.理解SCN的运作机制 ...