Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

Format Dictionary using input string in python

I am using below code to scrape data from website, where three fields are filled by user input.

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()

But I am getting error like this

{'exceptionMessage': 'Input string was not in a correct format.', 'exceptionType': 'System.FormatException', 'message': 'An error has occurred.', 'stackTrace': ' at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at BrowserView.Models.SearchCriteria.Parse() at BrowserView.Controllers.SearchController.SearchTwo(SearchCriteria criteria)'}

i want the code given below

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

to be like this when user inputs data

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the problem is only in inserting variable into your json then try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...