python -第七节课之网络请求,使用python工具模拟客户端发送请求

学习是为了做接口自动化,是为了发送请求

需要使用requrest模块 

import requests
import json
url = 'http://127.0.0.1:8999/login'
data = {'username':'niuhanyang2','password':'1'}
#get、post、传cookie、headers、传文件、传json、下载文件
#get请求
# r = requests.get(url,data)
print(r.text)#字符串格式返回
print(r.json())#字典
print(r.content)#返回bytes类型
print(r.status_code)#返回状态码
什么使用用什么方法,
测试接口有没有通过,返回状态码
从返回的数据里面取值,获取某个字典的值需要用.json这是返回一个字典,将josn串转成字典
什么时候用字符串,有时候访问一个网站,获取网页信息,需要用text
什么时候用content,有时候你要下载图片,下载文件都是二进制的东西,所以需要这种方法

#params是把参数传到url后头的方法
#Cookie: 
cookie = {'wp-settings-1':'1','PHPSESSID':'xxxxx'}
headers = {
'user-agent':'xxxx',
'cookie':'wp-settings-1=libraryContent%3Dbrowse%26posts_list_mode%3Dexcerpt%26editor%3Dtinymce%26post_dfw%3Doff%26imgsize%3Dfull%26editor_plain_text_paste_warning%3D1%26hidetb%3D1; wp-settings-time-1=1573143656; comment_author_8ec14a05b6903cd9021ece26c7b908a0=111; PHPSESSID=2e33445700b8381f67cafb40ee147480'}
# r = requests.post(url,data=data,params={"version":1.0},cookies=cookie)# 第一种 
# r = requests.post(url,data=data,params={"version":1.0},headers=headers)  第二种 
 


POST请求
第一种常用post请求

import requests
import json
url = 'http://127.0.0.1:8999/login'
data = {'username':'niuhanyang2','password':'1'}
#Cookie:
cookie = {'wp-settings-1':'1','PHPSESSID':'xxxxx'}
headers = {
'user-agent':'xxxx',
'cookie':'wp-settings-1=libraryContent%3Dbrowse%26posts_list_mode%3Dexcerpt%26editor%3Dtinymce%26post_dfw%3Doff%26imgsize%3Dfull%26editor_plain_text_paste_warning%3D1%26hidetb%3D1; wp-settings-time-1=1573143656; comment_author_8ec14a05b6903cd9021ece26c7b908a0=111; PHPSESSID=2e33445700b8381f67cafb40ee147480'}
r = requests.post(url,data=data,params={"version":1.0},cookies=cookie)#
r = requests.post(url,data=data,params={"version":1.0},headers=headers)


post和get传文件方法、
import requests
# r = requests.post(url,json=data)

# url = 'http://api.nnzhp.cn/api/file/file_upload'
# data = {'file':open('shuaige.xls','rb')}
# r = requests.post(url,files=data)
下载文件方法
拿到下载文件地址,打开文件把他写进去逻辑
r = requests.get('https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=293407302,1362956882&fm=26&gp=0.jpg',verify=False)
f = open('a.jpg','wb')
f.write(r.content)
f.close()
print(r.status_code) #返回的状态码


 
原文地址:https://www.cnblogs.com/weilemeizi/p/13697060.html