无法使用robotframework的RequestsLibrary访问json数据:类型错误:应为字符串或缓冲区
在下面三个测试用例中,Get Requests1、Get Requests2和Get Requests3。我试图通过三种不同的方式获取/response/result节点值,但它显示了相同的错误无法使用robotframework的RequestsLibrary访问json数据:类型错误:应为字符串或缓冲区,robotframework,Robotframework,在下面三个测试用例中,Get Requests1、Get Requests2和Get Requests3。我试图通过三种不同的方式获取/response/result节点值,但它显示了相同的错误 *** Settings *** Library Collections Library OperatingSystem Library HttpLibrary.HTTP Library RequestsLibrary *** Test Cases *** Get Requests1
*** Settings ***
Library Collections
Library OperatingSystem
Library HttpLibrary.HTTP
Library RequestsLibrary
*** Test Cases ***
Get Requests1
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response, now tring to get node value of /RestResponse/result
${getResponseJson} Get Json Value ${resp} /RestResponse/result
# shows error TypeError: expected string or buffer
log ${getResponseJson.content}
Get Requests2
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response, now tring to get node value of /RestResponse/result
${responseContent}= to json ${resp.content}
# shows error TypeError: expected string or buffer
${getResponseJson} Get Json Value ${responseContent} /RestResponse/result
log ${getResponseJson.content}
Get Requests3
# create a HTTP session to a server
Create Session countryname http://services.groupkt.com
# store response
${resp}= Get Request countryname /country/get/all
log ${resp.content}
# ${resp.content} display entire json response,parse json
${data} Parse Json ${resp}
# shows error TypeError: expected string or buffer
${getResponseJson} Get Json Value ${resp} /RestResponse/result
Json文件响应
您需要从Json而不是从请求对象调用
Get Json Value
。在代码中,${resp}
是一个包含JSON数据以及JSON解析器不知道的其他内容的对象
${getResponseJson} Get Json Value ${resp.content} /RestResponse/result
${resp}
是一个python对象。它有json数据,但也有HTTP返回代码和其他信息。您不能将其传递给任何接受JSON的对象
${resp.content}
是HTTP响应的主体。正如您在注释中所写,这是JSON数据。任何接受JSON数据的关键字都应该接受这一点
${resp.json}
是转换为python对象的响应的json字符串。它不再是JSON,而是python字典。您不能将其传递给任何需要JSON的函数。但是,您可以将其视为普通python字典
运行代码后,
${getResponseJson}
将获得您期望的数据。这是一个unicode字符串,unicode字符串没有content
属性。谢谢回复。我已尝试使用${resp.content}。它显示${getResponseJson.content}失败:AttributeError:'unicode'对象没有属性'content'。我还尝试使用${resp.json},显示TypeError:预期为字符串或buffer@madhur:请仔细查看我键入的内容、您键入的内容以及您自己的结果。在您的评论中,您说${resp.content}
显示json字符串。该字符串就是您需要搜索其他数据的字符串。不是${getResponseJson.content}
,也不是${resp.json}
。毫无疑问,${resp.content}显示json字符串。但是当我试图访问这个变量时,库方法显示了问题中提到的错误。@madhur:当我做出我在回答中提到的确切更改时,您的GetRequests1
测试通过了。
${getResponseJson} Get Json Value ${resp.content} /RestResponse/result