【问题标题】:Format Dictionary using input string in python使用python中的输入字符串格式化字典
【发布时间】:2020-12-31 20:23:24
【问题描述】:

我正在使用下面的代码从网站上抓取数据,其中三个字段由用户输入填充。

import requests 
import json
  

URL = "http://example.com"
  
docs = input("Doc type: ")
fromdate = input("From: ")
todate = input("To: ")

r = requests.post(url = URL, json = {"MaxRows":0,"RowsPerPage":0,"StartRow":0,"DocTypes":'"{}"',"FromDate":'"{}"',"ToDate":'"{}"'.format(docs,fromdate,todate)})
r.json()

但是我遇到了这样的错误

{'exceptionMessage': '输入字符串的格式不正确。', 'exceptionType': 'System.FormatException', 'message': '一个错误有 发生。','stackTrace':'在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)\r\n 在 System.Number.ParseInt32(String s、NumberStyles 样式、NumberFormatInfo 信息)\r\n at BrowserView.Models.SearchCriteria.Parse()\r\n at BrowserView.Controllers.SearchController.SearchTwo(SearchCriteria 条件)'}

我想要下面给出的代码

json = {"MaxRows":0,"RowsPerPage":0,"StartRow":0,"DocTypes":'"{}"',"FromDate":'"{}"',"ToDate":'"{}"'.format(docs,fromdate,todate)}

当用户输入数据时是这样的

json = {"MaxRows":0,"RowsPerPage":0,"StartRow":0,"DocTypes":"TAX","FromDate":"20201104","ToDate":"20201218"}

【问题讨论】:

    标签: python python-requests python-jsons python-requests-json


    【解决方案1】:

    如果问题只是在你的 json 中插入变量,那么试试这个:

    r = requests.post(url=URL, json={"MaxRows":0,"RowsPerPage":0,"StartRow":0,"DocTypes":f'{docs}',"FromDate":f'{fromdate}',"ToDate":f'{todate}'})
    

    【讨论】:

    • docsfromdatetodate 已经是字符串,因此不需要 f 字符串。例如,只需使用"DocTypes":docs
    【解决方案2】:

    这个怎么样:

    r = requests.post(url=URL, json= 
        {
          "MaxRows": 0,
          "RowsPerPage": 0,
          "StartRow": 0,
          "DocTypes": docs,
          "FromDate": fromdate,
          "ToDate": todate
         })
    

    input() 会将每个值作为字符串返回,不需要格式字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2012-03-01
      • 2011-08-22
      相关资源
      最近更新 更多