python学习接口测试(二)

1.python接口之http请求
python的强大之处在于提供了很多的标准库以及第三库,本文介绍urllib

和第三库的requests。

Urllib 定义了很多函数和类,这些函数和类能够帮助我们在复杂的情况下获取url内容。复杂情况— 基本的和深入的验证, 重定向, cookies 等等

2.requests的GET请求代码如下:


# response=requests.get('http://httpbin.org/get?name=gemey&age=22')

data={
'name':'tom',
'age':20
}
response=requests.get('http://httpbin.org/get', params=data)
# print(response.status_code) # 打印状态码
# print(response.url) # 打印请求url
# print(response.headers) # 打印头信息
# print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
# print(response.content) #以字节流形式打印

 3.Urllib的GET请求代码如下:

import urllib.request

url='http://www.baidu.com'

response=urllib.request.Request(url=url)

html=urllib.request.urlopen(response)

print(html.getcode())

print(html.headers)

请求结果:

200
Bdpagetype: 1
Bdqid: 0x8356551800064134
Cache-Control: private
Content-Type: text/html
Cxy_all: baidu+e5a8ce572d979b514b736b0cea852f5d
Date: Fri, 08 Jun 2018 01:21:13 GMT
Expires: Fri, 08 Jun 2018 01:20:22 GMT
P3p: CP=" OTI DSP COR IVA OUR IND COM "
Server: BWS/1.1
Set-Cookie: BAIDUID=2B497098824EEEF8A1B592EBC590946D:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=2B497098824EEEF8A1B592EBC590946D; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1528420873; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: BD_HOME=0; path=/
Set-Cookie: H_PS_PSSID=1436_21112_26350_26579_22159; path=/; domain=.baidu.com
Vary: Accept-Encoding
X-Ua-Compatible: IE=Edge,chrome=1
Connection: close
Transfer-Encoding: chunked

Urllib的Post请求,代码:

import urllib.request

import urllib.parse

url='http://www.tuling123.com/openapi/api'

data={"key": "your", "info": '你好'}



data=urllib.parse.urlencode(data).encode('utf-8')

re=urllib.request.Request(url,data)

html=urllib.request.urlopen(re)



print(html.getcode(),html.msg)

print(html.read())

请求结果:

200 OK
b'{"code":40001,"text":"\xe4\xba\xb2\xe7\x88\xb1\xe7\x9a\x84\xef\xbc\x8ckey\xe4\xb8\x8d\xe5\xaf\xb9\xe5\x93\xa6\xe3\x80\x82"}'
[Finished in 0.7s]

requests  post请求:

url='http://www.tuling123.com/openapi/api'

data={"key": "your", "info": '你好'}


response = requests.post('http://www.tuling123.com/openapi/api', data=data)

print(response.status_code) # 打印状态码
print(response.url) # 打印请求url
print(response.headers) # 打印头信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
print(response.content) #以字节流形式打印

结果:

在来一个:

import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

猜你喜欢

转载自www.cnblogs.com/dangkai/p/9153953.html
今日推荐