【问题标题】:JSON save to file get methodJSON保存到文件获取方法
【发布时间】:2018-06-08 09:24:46
【问题描述】:

我的代码:

def saveJSONget(site, code):
        response = requests.get(site)
        json_str = json.dumps(response.json())
        if not response.status_code == code:
            file = open("PATH", 'w')
            file.write(str(response.text) + "\n")

我需要将所有信息保存到 json 文件中:标头响应和请求、请求负载。我不知道要使用什么函数,即写入文件这个元素。我还有第二个问题。

如何改变我的方法? 错误:

Error
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
    yield
  File "/usr/lib/python3.6/unittest/case.py", line 601, in run
    self.setUp()
  File "PATH", line 13, in setUp
    Class.method(site, 210)
  File "PATHy", line 171, in method
    json_str = json.dumps(response.json())
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

谢谢你的帮助

【问题讨论】:

    标签: python json selenium post get


    【解决方案1】:
    from 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")
    

    【讨论】:

    • 谢谢。我如何编写 -> 请求标头、响应标头和 POST 方法 - 请求有效负载?
    • r = requests.get(url, headers={'key': 'value'})docs.python-requests.org
    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2017-10-17
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多