如何解析来自request.get()的响应?

时间:2018-12-08 00:19:15

标签: python python-requests

以下代码以文本格式返回响应:

val = https://service-smthing.com/info.txt
response = requests.get(val).content
print response
Response -

tag = unique-tag
buildNo = 1234
description = some description

如何从这样的纯文本响应中解析buildNo?另外,我尝试并且无法解析或使用loads()response.headers()等响应函数,方法与json响应相同。

2 个答案:

答案 0 :(得分:0)

您需要自己解析内容,但这只是在每行的等号上进行分割:

response = requests.get(val).content.decode('utf-8')
result = {}
for line in response.splitlines():
    k,v = line.split(' = ')
    result[k] = v

print (result)

返回:

{'tag': 'unique-tag', 'buildNo': '1234', 'description': 'some description'}

答案 1 :(得分:0)

使用字典理解:

response = '''Response - 

tag = unique-tag
buildNo = 1234
description = some description'''

data = {line.split(' = ')[0]: line.split(' = ')[1] for line in response.splitlines()[2:]}

结果:

print(data)
{'tag': 'unique-tag', 'buildNo': '1234', 'description': 'some description'}