将数据保存到文件.txt - 请求标头,响应标头和POST方法 - 请求有效负载

时间:2018-06-08 17:08:05

标签: python python-requests

pathlib import Path

def saveJSONget(site, code):
    r = requests.get(site)
    json_str = r.text
    if r.status_code != code:
        Path("PATH").write_text(r.text+"\n")

我试图将json保存到文件.txt。我是否需要保存有关请求标头响应标头以及POST方法 - 请求有效负载的信息?

用于保存此信息的功能是什么?

1 个答案:

答案 0 :(得分:0)

pathlib只是处理OS路径。您应该使用open方法将数据保存到文件中。

if r.status_code != code:
    with open('path/to/file/filename.txt', 'w') as fp;
        fp.write(r.text)

有关请求的信息可以在请求对象找到。

>>> r = requests.get('http://127.0.0.1:8000')

>>> r.status_code
200

>>> r.headers
{'Date': 'Fri, 08 Jun 2018 21:14:03 GMT', 'Content-Type': 'text/html; charset=utf-8', 'Vary': 'Cookie', 'Set-Cookie': 'csrftoken=pByJEeBKWtPMrZdpSxzAMpvGod6aqmIf; expires=Fri, 07-Jun-2019 21:14:03 GMT; Max-Age=31449600; Path=/', 'Server': 'WSGIServer/0.1 Python/2.7.12'}

>>> r.request.headers
{'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.18.4'}

>>> r.request.method
'GET'

有关详细信息,请查看requests官方文档。

相关问题