Python 3.x基于Xml数据的Http请求方法
作者:BarackHusseinObama 时间:2021-05-17 23:45:18
1. 前言
由于公司的一个项目是基于B/S架构与WEB服务通信,使用XML数据作为通信数据,在添加新功能时,WEB端与客户端分别由不同的部门负责,所以在WEB端功能实现过程中,需要自己发起请求测试,于是便选择了使用Python编写此脚本。另外由于此脚本最开始希望能在以后发展成具有压力测试的功能,所以除了基本的访问之外,添加了多线程请求。
整个脚本主要涉及到的关于Python的知识点包括:
基于urllib.request的Http访问
多线程
类与方法的定义
全局变量的定义与使用
文件的读取与写入
……
2. 源码与结果
整个程序包括Python源码和配置文件,由于源码中有相应的注释,所以就直接贴源码吧,如下:
# TradeWeb测试脚本
import threading, time, http.client, urllib.request, os
#import matplotlib.pyplot as plt
URL = 'http://127.0.0.1:8888/XXXXXXXXX/httpXmlServlet' # 在配置文件中读取,此处将无效
TOTAL = 0; # 总数
SUCC = 0; # 响应成功数量
FAIL = 0; # 响应失败数量
EXCEPT = 0 # 响应异常数
MAXTIME = 0 # 最大响应时间
MINTIME = 100 # 最小响应时间,初始值为100秒
COUNT_TIME = 0 # 总时间
THREAD_COUNT = 0 # 记录线程数量
CODE_MAP = {200:0, 301:0, 302:0, 304:0} # 状态码信息(部分)
RESULT_FILE = 'tradeWebResult.xml' # 输出结果文件
REQUEST_DATA_FILE = 'requestData.config' # 数据文件
DATA = '''请在tradeWebRequestData.config文件中配置'''
TIME_LIST = [] # 记录访问时间
#创建一个threading.Thread的派生类
class RequestThread(threading.Thread):
#构造函数
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.test_count = 0;
#线程运行的入口函数
def run(self):
global THREAD_COUNT
THREAD_COUNT += 1
#print("Start the count of thread:%d" %(THREAD_COUNT))
self.testPerformace()
#测试性能方法
def testPerformace(self):
global TOTAL
global SUCC
global FAIL
global EXCEPT
global DATA
global COUNT_TIME
global CODE_MAP
global URL
try:
st = time.time() #记录开始时间
start_time
cookies = urllib.request.HTTPCookieProcessor()
opener = urllib.request.build_opener(cookies)
resp = urllib.request.Request(url=URL,
headers={'Content-Type':'text/xml', 'Connection':'Keep-Alive'},
data=DATA.encode('gbk'))
respResult = opener.open(resp)
# 记录状态码 START
code = respResult.getcode()
if code == 200:
SUCC += 1
else:
FAIL += 1
if code in CODE_MAP.keys():
CODE_MAP[code] += 1
else:
CODE_MAP[code] = 1
# print(request.status)
# 记录状态码 END
html = respResult.read().decode('gbk')
print(html)
time_span = time.time() - st # 计算访问时间
# 记录访问时间
TIME_LIST.append(round(time_span * 1000))
# print('%-13s: %f ' %(self.name, time_span))
self.maxtime(time_span)
self.mintime(time_span)
self.writeToFile(html)
# info = respResult.info() # 响应头信息
# url = respResult.geturl() # URL地址
# print(info);
# print(url)
COUNT_TIME += time_span
TOTAL += 1
except Exception as e:
print(e)
TOTAL += 1
EXCEPT += 1
# 设置最大时间,如果传入的时间大于当前最大时间
def maxtime(self, ts):
global MAXTIME
#print("time:%f" %(ts))
if ts > MAXTIME:
MAXTIME = ts
# 设置最小时间,如果传入的时间小于当前最小时间
def mintime(self, ts):
global MINTIME
#print("time:%f" %(ts))
if ts < MINTIME and ts > 0.000000000000000001:
MINTIME = ts
# 写入文件
def writeToFile(self, html):
f = open(RESULT_FILE, 'w')
f.write(html)
f.write('\r\n')
f.close();
# 读取XML数据信息
def loadData():
global URL
global DATA
f = open(REQUEST_DATA_FILE, 'r')
URL = "".join(f.readline())
DATA = "".join(f.readlines())
# print(DATA)
f.close()
if __name__ == "__main__":
# print("============测试开始============")
print("")
# 开始时间
start_time = time.time()
# 并发的线程数
thread_count = 1
loadData() # 加载请求数据
i = 0
while i < thread_count:
t = RequestThread("Thread" + str(i))
t.start()
i += 1
t = 0
while TOTAL < thread_count and t < 60:
# print("total:%d, succ:%d, fail:%d, except:%d\n" %(TOTAL,SUCC,FAIL,EXCEPT))
print("正在请求 ",URL)
t += 1
time.sleep(1)
# 打印信息
print()
print("请求", URL, "的统计信息:")
print(" 总请求数 = %d,成功 = %d,失败 = %d,异常 = %d" %(TOTAL, SUCC, FAIL, EXCEPT))
print()
print("往返程的估计时间(以毫秒为单位):")
print(" 合计 =", int(COUNT_TIME * 1000), "ms", end = '')
print(" 最大 =", round(MAXTIME * 1000), "ms", end = '')
print(" 最小 =", round(MINTIME * 1000), "ms", end = '')
print(" 平均 =", round((COUNT_TIME / thread_count) * 1000), "ms")
print()
print("响应的状态码与次数信息(状态码:次数):")
print(" ", CODE_MAP)
print()
print("输出页面请查看", RESULT_FILE, "文件(建议使用浏览器或XML专业工具打开)")
print()
# os.system("pause")
print(TIME_LIST)
input()
配置文件主要在于易于更改访问路径等,其中SESSION_ID是在Fiddler中抓包获取,配置文件源文件如下(为不泄露公司隐私,数据并非原始数据,但格式相同):
http://127.0.0.1:8888/XXXXXXXXX/httpXmlServlet
<?xml version=“1.0” encoding = “GB2312”?>
<COM>
<REQ name="commodity_query">
<USER_ID>0001</USER_ID>
<COMMODITY_ID>0000</COMMODITY_ID>
<SESSION_ID>4918081208706966071</SESSION_ID>
</REQ>
</COM>
测试结果如下:
由于公司保密性要求,地址做了模糊处理,另外输出的tradeWebResult.xml结果页面也未展示。
以上仅为个人学习与使用Python过程的一个记录,难免会有程序设计或使用不当,如有更好的意见,欢迎指正。
注:此代码开发环境为Python 3.5 + windows,未在Python 2.x环境下测试
来源:https://blog.csdn.net/t894690230/article/details/50598718
标签:Python,Xml,Http
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于keras 模型、结构、权重保存的实现
2022-12-20 06:31:22
六行python代码的爱心曲线详解
2022-04-09 23:15:17
![](https://img.aspxhome.com/file/2023/3/114663_0s.png)
基于Python实现超级玛丽游戏的示例代码
2022-02-14 16:48:00
![](https://img.aspxhome.com/file/2023/3/72773_0s.gif)
一篇文章带你详细了解python中一些好用的库
2022-03-18 09:02:19
![](https://img.aspxhome.com/file/2023/4/99044_0s.jpg)
python代码实现学生信息管理系统
2023-02-06 18:31:34
![](https://img.aspxhome.com/file/2023/7/83917_0s.jpg)
SqlServer 基础知识 数据检索、查询排序语句
2011-11-03 16:46:12
树莓派用python中的OpenCV输出USB摄像头画面
2023-11-04 12:12:49
![](https://img.aspxhome.com/file/2023/1/85271_0s.jpg)
Python图像处理之图像的缩放、旋转与翻转实现方法示例
2023-03-09 11:25:20
![](https://img.aspxhome.com/file/2023/4/93794_0s.jpg)
Python双精度浮点数运算并分行显示操作示例
2024-01-01 21:33:10
![](https://img.aspxhome.com/file/2023/4/105254_0s.jpg)
python中的txt文件转换为XML
2021-12-05 10:45:48
![](https://img.aspxhome.com/file/2023/0/67310_0s.png)
python 基于空间相似度的K-means轨迹聚类的实现
2022-10-24 07:29:02
![](https://img.aspxhome.com/file/2023/4/90294_0s.png)
使用pycallgraph分析python代码函数调用流程以及框架解析
2023-06-05 08:52:56
![](https://img.aspxhome.com/file/2023/2/100842_0s.png)
HTML头部属性全接触
2007-09-05 19:09:00
中秋阴天看不见月亮只好用python写赏月工具
2021-02-09 17:54:24
![](https://img.aspxhome.com/file/2023/3/96453_0s.gif)
详解Python字典查找性能
2022-05-06 10:45:34
SQL Server SA权限最新入侵方法
2009-03-25 16:56:00
对PyQt5的输入对话框使用(QInputDialog)详解
2021-12-24 19:52:27
![](https://img.aspxhome.com/file/2023/2/125052_0s.jpg)
详解Python中的type和object
2021-03-25 13:00:58
![](https://img.aspxhome.com/file/2023/1/67921_0s.png)
仅用50行Python代码实现一个简单的代理服务器
2022-11-26 14:44:57
Asp生成RSS的类_给网站加上RSS
2011-04-19 11:06:00