【iTestCat】python3+requests实现接口自动化教程

通过python实现接口自动化测试主要借助requests库来实现。requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,支持python3。这是一个第三方的的库,在使用前需要安装。

 

1、使用pip安装

安装命令pip install requests

 

【iTestCat】python3+requests实现接口自动化教程

2、HTTP 请求

2.1、HTTP 请求由三部分构成:

1)请求行

包括:请求方式,请求的资源路径,协议版本

请求方式有很多种,常用就两种GET和POST。

GET和POST的区别?

GET:请求的参数会显示到地址栏。通常是有大小的限制。没有请求体

POST:请求的参数不会显示到地址栏(在请求体中)。POST没有大小的限制。有请求体(请求参数)。只有表单设置method=”post”才是post请求。

2)请求头

请求头的格式一般都是一个key对应一个value的,也有一个key对应多个value的情况。

记住一些请求头:

Referer:代表网页的来源。(防盗链)。

User-Agent:获得客户端浏览器类型。

3)请求体

只有POST请求方式才有请求体,而且请求体是POST方式请求参数。

2.2 request提供的请求

requests 提供了几乎所有 HTTP 动词的功能:GET、OPTIONS、HEAD、POST、PUT、PATCH、DELETE,另外,它提供了?headers?参数让我们根据需求定制请求头。

使用 Requests 发送一个请求很方便,比如:

 

3、请求

3.1 、基本GET请求

3.1.1、基本写法

3.1.2、带参数的GET请求

3.1.3、带参数的GET请求(2)

3.1.4、解析json

3.1.5、获取二进制数据

import requests

response = requests.get(‘http://github.com/favicon.ico’)

# str,bytes

print(type(response.text),type(response.content))

# 输出响应的文本内容

print(response.text)

# 输出响应的二进制内容

print(response.content)

# 下载二进制数据到本地

with?open(‘favicon.ico’,’wb’)as?f:

f.write(response.content)

f.close()

 

3.1.6、添加headers

import requests

# 设置User-Agent浏览器信息

headers = {

“User-Agent”:”Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36″

}

# 设置请求头信息

response = requests.get(‘https://www.zhihu.com/explore’,headers=headers)

print(response.text)

 

3.2、基本POST请求

import requests

# 设置传入post表单信息

data= {‘name’:’jyx’,’age’:18}

# 设置请求头信息

headers = {

“User-Agent”:”Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36″

}

# 设置请求头信息和POST请求参数(data)

response = requests.post(‘http://httpbin.org/post’, data=data, headers=headers)

print(response.text)

 

4、响应

HTTP 响应与 HTTP 请求相似,由三部分组成:

状态行:包含 HTTP 协议版本、状态码和状态描述,以空格分隔

响应头:包含一系列的键值对

响应正文

1)对于响应状态码,我们可以访问响应对象的?status_code?属性:

import requests

r = requests.get(“http://httpbin.org/get”)

print(r.status_code)

2)对于响应正文,我们可以通过多种方式读取,比如:

普通响应,使用r.text获取

JSON 响应,使用r.json()获取

二进制响应,使用r.content获取

原始响应,使用r.raw获取

4.1 response属性

import requests

response = requests.get(‘http://www.jianshu.com/’)

# 获取响应状态码

print(type(response.status_code),response.status_code)

# 获取响应头信息

print(type(response.headers),response.headers)

# 获取响应头中的cookies

print(type(response.cookies),response.cookies)

# 获取访问的url

print(type(response.url),response.url)

# 获取访问的历史记录

print(type(response.history),response.history)

4.2、 状态码判断

import requests

response = requests.get(‘http://www.jianshu.com/404.html’)

# 使用request内置的字母判断状态码

ifnot?response.status_code == requests.codes.ok:

print(‘404-1’)

response = requests.get(‘http://www.jianshu.com’)

# 使用状态码数字判断

ifnot?response.status_code ==200:

print(‘404-2’)

4.3 requests内置的状态字符

100: (‘continue’,),

101: (‘switching_protocols’,),

102: (‘processing’,),

103: (‘checkpoint’,),

122: (‘uri_too_long’, ‘request_uri_too_long’),

200: (‘ok’, ‘okay’, ‘all_ok’, ‘all_okay’, ‘all_good’, ‘\\o/’, ‘?’),

201: (‘created’,),

202: (‘accepted’,),

203: (‘non_authoritative_info’, ‘non_authoritative_information’),

204: (‘no_content’,),

205: (‘reset_content’, ‘reset’),

206: (‘partial_content’, ‘partial’),

207: (‘multi_status’, ‘multiple_status’, ‘multi_stati’, ‘multiple_stati’),

208: (‘already_reported’,),

226: (‘im_used’,),

# Redirection.

300: (‘multiple_choices’,),

301: (‘moved_permanently’, ‘moved’, ‘\\’),

302: (‘found’,),

303: (‘see_other’, ‘other’),

304: (‘not_modified’,),

305: (‘use_proxy’,),

306: (‘switch_proxy’,),

307: (‘temporary_redirect’, ‘temporary_moved’, ‘temporary’),

308: (‘permanent_redirect’,?’resume_incomplete’, ‘resume’,), # These 2 to be removed in 3.0

# Client Error.

400: (‘bad_request’, ‘bad’),

401: (‘unauthorized’,),

402: (‘payment_required’, ‘payment’),

403: (‘forbidden’,),

404: (‘not_found’, ‘-‘),

405: (‘method_not_allowed’, ‘not_allowed’),

406: (‘not_acceptable’,),

407:(‘proxy_authentication_required’,’proxy_auth’,’proxy_authentication’),

408: (‘request_timeout’, ‘timeout’),

409: (‘conflict’,),

410: (‘gone’,),

411: (‘length_required’,),

412: (‘precondition_failed’, ‘precondition’),

413: (‘request_entity_too_large’,),

414: (‘request_uri_too_large’,),

415: (‘unsupported_media_type’, ‘unsupported_media’, ‘media_type’),

416:(‘requested_range_not_satisfiable’,’requested_range’,’range_not_satisfiable’),

417: (‘expectation_failed’,),

418: (‘im_a_teapot’, ‘teapot’, ‘i_am_a_teapot’),

421: (‘misdirected_request’,),

422: (‘unprocessable_entity’, ‘unprocessable’),

423: (‘locked’,),

424: (‘failed_dependency’, ‘dependency’),

425: (‘unordered_collection’, ‘unordered’),

426: (‘upgrade_required’, ‘upgrade’),

428: (‘precondition_required’, ‘precondition’),

429: (‘too_many_requests’, ‘too_many’),

431: (‘header_fields_too_large’, ‘fields_too_large’),

444: (‘no_response’, ‘none’),

449: (‘retry_with’, ‘retry’),

450: (‘blocked_by_windows_parental_controls’, ‘parental_controls’),

451: (‘unavailable_for_legal_reasons’, ‘legal_reasons’),

499: (‘client_closed_request’,),

# Server Error.

500: (‘internal_server_error’, ‘server_error’, ‘/o\\’, ‘?’),

501: (‘not_implemented’,),

502: (‘bad_gateway’,),

503: (‘service_unavailable’, ‘unavailable’),

504: (‘gateway_timeout’,),

505: (‘http_version_not_supported’, ‘http_version’),

506: (‘variant_also_negotiates’,),

507: (‘insufficient_storage’,),

509: (‘bandwidth_limit_exceeded’, ‘bandwidth’),

510: (‘not_extended’,),

511:(‘network_authentication_required’,’network_auth’,’network_authentication’),

5、高级操作

5.1、文件上传

import requests

files = {‘file’:open(‘favicon.ico’,’rb’)}

# 往POST请求头中设置文件(files)

response = requests.post(‘http://httpbin.org/post’,files=files)

print(response.text)

5.2、获取cookies

HTTP 协议是无状态的,这意味着每个请求都是独立的,如果后续的处理需要用到前面的信息,则数据需要重传,为了解决这个问题,我们可以使用 Cookie 或 Session 来存储某些特定的信息,比如用户名、密码等,这样,当用户在不同 Web 页面跳转或再次登录网站时,就不用重新输入用户名和密码(当然,如果 Cookie 被删除和 Session 过期则需要重新输入)。

Requests 提供了会话对象让我们能够跨请求保持某些参数,也可以在同一个 Session 实例发出的所有请求之间保持 Cookie。比如:

import requests

response = requests.get(‘https://www.baidu.com’)

print(response.cookies)

for?key,value?in?response.cookies.items():

print(key,’=====’,value)

5.3、会话维持

5.3.1、普通请求

import requests

requests.get(‘http://httpbin.org/cookies/set/number/12456’)

response = requests.get(‘http://httpbin.org/cookies’)

# 本质上是两次不同的请求,session不一致

print(response.text)

5.3.2、会话维持请求

import requests

# 从Requests中获取session

session = requests.session()

# 使用seesion去请求保证了请求是同一个session

session.get(‘http://httpbin.org/cookies/set/number/12456’)

response = session.get(‘http://httpbin.org/cookies’)

print(response.text)

5.4、证书验证

5.4.1、无证书访问

import requests

response = requests.get(‘https://www.12306.cn’)

# 在请求https时,request会进行证书的验证,如果验证失败则会抛出异常

print(response.status_code)

5.4.2、关闭证书验证

import requests

# 关闭验证,但是仍然会报出证书警告

response = requests.get(‘https://www.12306.cn’,verify=False)

print(response.status_code)

5.4.3、消除关闭证书验证的警告

from requests.packages import urllib3

import requests

# 关闭警告

urllib3.disable_warnings()

response = requests.get(‘https://www.12306.cn’,verify=False)

print(response.status_code)

5.4.4、手动设置证书

import requests

# 设置本地证书

response=requests.get(‘https://www.12306.cn’,cert=(‘/path/server.crt’,’/path/key’))

print(response.status_code)

5.5、代理设置

5.5.1、设置普通代理

如果需要使用 HTTP 代理,我们可以为任意请求方法提供?proxies?参数

import requests

proxies = {

“http”:”http://127.0.0.1:9743″,

“https”:”https://127.0.0.1:9743″,

}

# 往请求中设置代理(proxies

)

response = requests.get(“https://www.taobao.com”, proxies=proxies)

print(response.status_code)

5.5.2、设置带有用户名和密码的代理

import requests

proxies = {

“http”:”http://user:password@127.0.0.1:9743/”,

}

response = requests.get(“https://www.taobao.com”, proxies=proxies)

print(response.status_code)

5.5.3、设置socks代理

requests 自 2.10.0 版起,开始支持 SOCKS 协议的代理,如果要使用,我们还需安装一个第三方库:pip3 install requests[socks]

import requests

proxies = {

‘http’:’socks5://127.0.0.1:9742′,

‘https’:’socks5://127.0.0.1:9742′

}

response = requests.get(“https://www.taobao.com”, proxies=proxies)

print(response.status_code)

5.6、超时设置

5.7、认证设置

import requests

from requests.auth import HTTPBasicAuth

r = requests.get(‘http://120.27.34.24:9001’, auth=HTTPBasicAuth(‘user’,’123′))

print(r.status_code)

5.8、异常处理

 

 

原创文章,作者:iTestCat,保留所有权利,禁止转载,如若转载,请联系作者!

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
iTestCat的头像iTestCat
上一篇 2018年7月19日 下午5:45
下一篇 2018年7月21日 下午5:03

相关推荐

发表回复

登录后才能评论
Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Paito HK Toto4d Toto4d Paito Hk
Toto Slot
Toto Slot
Toto Slot
Toto Slot
Toto Slot
Togel Slot
SLOT GACOR
slot gacor
ts77casino
slot demo
slot dana
slot dana
Toto Slot
Situs Slot Online
Toto Slot
Toto Slot
situs slot online
slot maxwin
slot bola
slot bola
Toto Slot
slot88 gacor
bacan4d
Toto Slot
slot gacor
Slot Toto
slot gacor
Agen Slot Toto
slot gacor
Toto Slot
Situs Toto
toto gacor
Slot Online
slot qris
situs toto
https://himmahnw.id/
slot gacor
situs toto
slot toto
slot gacor
scatter hitam
situs slot online
situs slot online
pg soft mahjong 2
situs slot
situs slot
toto slot
situs toto
Toto Slot Gacor Akun Toto Akun Toto Akun Toto Akun Toto Situs Toto Akun Toto Akun Toto slot gacor slot gacor slot gacor terminal4d toto slot toto slot toto slot toto slot toto 4d
Toto SLot Toto SLot Toto SLot Togel Slot Togel Slot Toto Slot Toto Slot Toto Slot Toto Slot Toto Slot Toto Slot
Toto SLot Toto SLot
Toto Slot
https://hamadtrainingcenter.com/
https://keepod.it/
https://orologilegno.it/
https://metaldetectoronline.it/
https://winestation.it/
https://armandotravaglini.it/
https://digitalmarketingturistico.it/
https://gotodigitally.it/
situs slot
https://rockequipinc.com/
https://123jumping.com/
https://hancockcrimestoppers.org/
https://neuroscienceresearchlab.org/
https://sailingthe7zs.com/
https://pepelearningstudyportal.com/
https://arkinteriorsolutions.com/
https://shreeuniqueschool.com/
https://shreetherapy.com/
https://pepwhiz.com/
slot88
slot gacor
https://peptextandmore.com/
https://jainfoundation.in/
https://www.erflandscaping.co.uk/
https://sherrylynnespinosa.com/
https://nepalmarathons.com/
https://cciadvisory.org/
https://ablueservices.com/
situs slot
link slot
situs slot
situs slot
https://sanjoseedu.org/
https://quebradasyauco.org/
https://tap.bio/@terminal4dgacorr
https://rosariocialesedu.org/
https://rosariovegabajaedu.org/
situs slot
situs slot
situs slot
situs slot online
situs slot
situs slot
https://istanbulatakoyescort.net/
situs slot
https://letskini.com/
situs slot
situs slot
slot dana
situs slot
situs slot
agen slot
situs slot
situs slot
https://humas.unmuhbandung.ac.id/