使用Karate框架提取HTML API响应内容及解决readAsString报错求助
解决Karate框架提取HTML响应内容的错误及方法
错误原因
karate.readAsString()是用于读取本地文件内容的API,你传入response会被当作文件路径解析,自然会报“No such file or directory”错误。HTTP接口返回的响应体直接存在response变量中,不需要用这个方法转换。
正确提取HTML内容的方法
Karate支持直接将规范的HTML响应解析为类JSON结构,也可以用正则或XML路径语法提取内容,以下是几种可行方案:
方案1:利用Karate的HTML自动解析特性
Given xxx When xxx Then status 400 * print 'printing response' * print response # 直接使用response获取HTML响应体 * def html = response # 提取<head>中<title>标签的文本 * def titleContent = html.head.title # 提取<body>中第二个<center>标签的文本(第一个<center>包含400 Bad Request) * def centerContent = html.body.center[1] # 打印结果验证 * print titleContent * print centerContent
方案2:使用XML路径语法(适合结构规范的HTML)
Given xxx When xxx Then status 400 # 用xmlPath定位标签文本 * def titleContent = karate.xmlPath(response, '/html/head/title/text()') * def centerContent = karate.xmlPath(response, '/html/body/center[2]/text()') * print titleContent * print centerContent
方案3:使用正则匹配
如果HTML结构不规范,可以用正则提取:
Given xxx When xxx Then status 400 * def htmlText = response # 提取<title>内的内容 * def titleContent = karate.extract(htmlText, '<title>(.*?)</title>', 1) # 提取目标<center>内的内容 * def centerContent = karate.extract(htmlText, '<center>(Request Header Or Cookie Too Large)</center>', 1) * print titleContent * print centerContent
内容的提问来源于stack exchange,提问作者Ramii
相关产品推荐
相关产品推荐

